id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_3951_2
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 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/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; if (update->autoCalculateBitmapData) { bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int)bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int)palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static BOOL update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp, UINT32 flags) { BYTE* newMask; UINT32 scanlineSize; UINT32 max = 32; if (flags & LARGE_POINTER_FLAG_96x96) max = 96; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > max) || (pointer_color->height > max)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp, update->context->settings->LargePointerFlag)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer) { BYTE* newMask; UINT32 scanlineSize; if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 20) goto fail; Stream_Read_UINT16(s, pointer->xorBpp); Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */ Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */ if ((pointer->width > 384) || (pointer->height > 384)) goto fail; Stream_Read_UINT32(s, pointer->lengthAndMask); /* lengthAndMask (4 bytes) */ Stream_Read_UINT32(s, pointer->lengthXorMask); /* lengthXorMask (4 bytes) */ if (pointer->hotSpotX >= pointer->width) pointer->hotSpotX = 0; if (pointer->hotSpotY >= pointer->height) pointer->hotSpotY = 0; if (pointer->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer->lengthXorMask) goto fail; scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer->width, pointer->height, pointer->lengthXorMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask); if (!newMask) goto fail; pointer->xorMaskData = newMask; Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask); } if (pointer->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer->lengthAndMask) goto fail; scanlineSize = ((7 + pointer->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer->lengthAndMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->andMaskData, pointer->lengthAndMask); if (!newMask) goto fail; pointer->andMaskData = newMask; Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s) { POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE)); if (!pointer) goto fail; if (!_update_read_pointer_large(s, pointer)) goto fail; return pointer; fail: free_pointer_large_update(update->context, pointer); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp, update->context->settings->LargePointerFlag)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER_LARGE: { POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s); if (pointer_large) { rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large); free_pointer_large_update(context, pointer_large); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", update_type_to_string(updateType)); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL _update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) { if (!update_end_paint(update)) return FALSE; } s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL _update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update_end_paint(update); update_begin_paint(update); } } static void update_force_flush(rdpContext* context) { update_flush(context); } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update_begin_paint(update); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } static BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL); length += update_prepare_bounds(context, orderInfo); return length; } static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, get_primary_drawing_order_field_bytes(orderInfo->orderType, NULL)); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order( cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order( cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order(rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer->xorBpp); Stream_Write_UINT16(s, pointer->cacheIndex); Stream_Write_UINT16(s, pointer->hotSpotX); Stream_Write_UINT16(s, pointer->hotSpotY); Stream_Write_UINT16(s, pointer->width); Stream_Write_UINT16(s, pointer->height); Stream_Write_UINT32(s, pointer->lengthAndMask); Stream_Write_UINT32(s, pointer->lengthXorMask); Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask); Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_large(s, pointer)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { RECTANGLE_16* prect = NULL; RECTANGLE_16 rect = { 0 }; BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0) { if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16)) return FALSE; Stream_Read_UINT16(s, rect.left); Stream_Read_UINT16(s, rect.top); Stream_Read_UINT16(s, rect.right); Stream_Read_UINT16(s, rect.bottom); prect = &rect; } if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { UINT16 orderSize = 11; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) orderSize += 2 + stateOrder->titleInfo.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) orderSize += 2 + stateOrder->OverlayDescription.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) orderSize += 1; return orderSize; } static BOOL update_send_new_or_existing_window(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) Stream_Write_UINT32(s, stateOrder->ownerWindowId); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) { Stream_Write_UINT32(s, stateOrder->style); Stream_Write_UINT32(s, stateOrder->extendedStyle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) { Stream_Write_UINT8(s, stateOrder->showState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) { Stream_Write_UINT16(s, stateOrder->titleInfo.length); Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->clientOffsetX); Stream_Write_INT32(s, stateOrder->clientOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->clientAreaWidth); Stream_Write_UINT32(s, stateOrder->clientAreaHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginLeft); Stream_Write_UINT32(s, stateOrder->resizeMarginRight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginTop); Stream_Write_UINT32(s, stateOrder->resizeMarginBottom); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) { Stream_Write_UINT8(s, stateOrder->RPContent); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) { Stream_Write_UINT32(s, stateOrder->rootParentHandle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->windowOffsetX); Stream_Write_INT32(s, stateOrder->windowOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) { Stream_Write_INT32(s, stateOrder->windowClientDeltaX); Stream_Write_INT32(s, stateOrder->windowClientDeltaY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->windowWidth); Stream_Write_UINT32(s, stateOrder->windowHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) { Stream_Write_UINT16(s, stateOrder->numWindowRects); Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) { Stream_Write_UINT32(s, stateOrder->visibleOffsetX); Stream_Write_UINT32(s, stateOrder->visibleOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) { Stream_Write_UINT16(s, stateOrder->numVisibilityRects); Stream_Write(s, stateOrder->visibilityRects, stateOrder->numVisibilityRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) { Stream_Write_UINT16(s, stateOrder->OverlayDescription.length); Stream_Write(s, stateOrder->OverlayDescription.string, stateOrder->OverlayDescription.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) { Stream_Write_UINT8(s, stateOrder->TaskbarButton); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) { Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarEdge); } update->numberOrders++; return TRUE; } static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { UINT16 orderSize = 23; ICON_INFO* iconInfo = iconOrder->iconInfo; orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask; if (iconInfo->bpp <= 8) orderSize += 2 + iconInfo->cbColorTable; return orderSize; } static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); ICON_INFO* iconInfo = iconOrder->iconInfo; UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder); update_check_flush(context, orderSize); s = update->us; if (!s || !iconInfo) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */ if (iconInfo->bpp <= 8) { Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */ if (iconInfo->bpp <= 8) { Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_CACHED_ICON_ORDER* cachedIconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 14; CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 11; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_new_or_existing_notification_icons_order( const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { UINT16 orderSize = 15; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { orderSize += 2 + iconStateOrder->toolTip.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; orderSize += 12 + infoTip.text.length + infoTip.title.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { orderSize += 4; } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; orderSize += 12; if (iconInfo.bpp <= 8) orderSize += 2 + iconInfo.cbColorTable; orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor; } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { orderSize += 3; } return orderSize; } static BOOL update_send_new_or_existing_notification_icons(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); BOOL versionFieldPresent = FALSE; UINT16 orderSize = update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ /* Write body */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) { versionFieldPresent = TRUE; Stream_Write_UINT32(s, iconStateOrder->version); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { Stream_Write_UINT16(s, iconStateOrder->toolTip.length); Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; /* info tip should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */ Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */ Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */ Stream_Write(s, infoTip.text.string, infoTip.text.length); Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */ Stream_Write(s, infoTip.title.string, infoTip.title.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { /* notify state should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, iconStateOrder->state); } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */ if (iconInfo.bpp <= 8) { Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */ orderSize += iconInfo.cbBitsMask; if (iconInfo.bpp <= 8) { Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */ } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon; Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ } update->numberOrders++; return TRUE; } static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 15; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT16 orderSize = 7; if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { orderSize += 4; } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { orderSize += 1 + (4 * monitoredDesktop->numWindowIds); } return orderSize; } static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT32 i; wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */ } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */ /* windowIds */ for (i = 0; i < monitoredDesktop->numWindowIds; i++) { Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]); } } update->numberOrders++; return TRUE; } static BOOL update_send_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 7; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ update->numberOrders++; return TRUE; } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = _update_begin_paint; update->EndPaint = _update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->ServerStatusInfo = rdp_send_server_status_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerLarge = update_send_pointer_large; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; update->window->WindowCreate = update_send_window_create; update->window->WindowUpdate = update_send_window_update; update->window->WindowIcon = update_send_window_icon; update->window->WindowCachedIcon = update_send_window_cached_icon; update->window->WindowDelete = update_send_window_delete; update->window->NotifyIconCreate = update_send_notify_icon_create; update->window->NotifyIconUpdate = update_send_notify_icon_update; update->window->NotifyIconDelete = update_send_notify_icon_delete; update->window->MonitoredDesktop = update_send_monitored_desktop; update->window->NonMonitoredDesktop = update_send_non_monitored_desktop; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->OverlayDescription.string); free(window_state->titleInfo.string); free(window_state->windowRects); free(window_state->visibilityRects); memset(window_state, 0, sizeof(WINDOW_STATE_ORDER)); } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; WINPR_UNUSED(rdp); update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); InitializeCriticalSection(&(update->mux)); update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->autoCalculateBitmapData = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window); } MessageQueue_Free(update->queue); DeleteCriticalSection(&update->mux); free(update); } } BOOL update_begin_paint(rdpUpdate* update) { if (!update) return FALSE; EnterCriticalSection(&update->mux); if (!update->BeginPaint) return TRUE; return update->BeginPaint(update->context); } BOOL update_end_paint(rdpUpdate* update) { BOOL rc = FALSE; if (!update) return FALSE; if (update->EndPaint) rc = update->EndPaint(update->context); LeaveCriticalSection(&update->mux); return rc; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3951_2
crossvul-cpp_data_bad_2749_0
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2749_0
crossvul-cpp_data_good_2648_3
/* * Decode and print Zephyr packets. * * http://web.mit.edu/zephyr/doc/protocol * * Copyright (c) 2001 Nickolai Zeldovich <kolya@MIT.EDU> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * The name of the author(s) may not be used to endorse or promote * products derived from this software without specific prior written * permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. */ /* \summary: Zephyr printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "netdissect.h" struct z_packet { const char *version; int numfields; int kind; const char *uid; int port; int auth; int authlen; const char *authdata; const char *class; const char *inst; const char *opcode; const char *sender; const char *recipient; const char *format; int cksum; int multi; const char *multi_uid; /* Other fields follow here.. */ }; enum z_packet_type { Z_PACKET_UNSAFE = 0, Z_PACKET_UNACKED, Z_PACKET_ACKED, Z_PACKET_HMACK, Z_PACKET_HMCTL, Z_PACKET_SERVACK, Z_PACKET_SERVNAK, Z_PACKET_CLIENTACK, Z_PACKET_STAT }; static const struct tok z_types[] = { { Z_PACKET_UNSAFE, "unsafe" }, { Z_PACKET_UNACKED, "unacked" }, { Z_PACKET_ACKED, "acked" }, { Z_PACKET_HMACK, "hm-ack" }, { Z_PACKET_HMCTL, "hm-ctl" }, { Z_PACKET_SERVACK, "serv-ack" }, { Z_PACKET_SERVNAK, "serv-nak" }, { Z_PACKET_CLIENTACK, "client-ack" }, { Z_PACKET_STAT, "stat" }, { 0, NULL } }; static char z_buf[256]; static const char * parse_field(netdissect_options *ndo, const char **pptr, int *len) { const char *s; if (*len <= 0 || !pptr || !*pptr) return NULL; if (*pptr > (const char *) ndo->ndo_snapend) return NULL; s = *pptr; while (*pptr <= (const char *) ndo->ndo_snapend && *len >= 0 && **pptr) { (*pptr)++; (*len)--; } (*pptr)++; (*len)--; if (*len < 0 || *pptr > (const char *) ndo->ndo_snapend) return NULL; return s; } static const char * z_triple(const char *class, const char *inst, const char *recipient) { if (!*recipient) recipient = "*"; snprintf(z_buf, sizeof(z_buf), "<%s,%s,%s>", class, inst, recipient); z_buf[sizeof(z_buf)-1] = '\0'; return z_buf; } static const char * str_to_lower(const char *string) { char *zb_string; strncpy(z_buf, string, sizeof(z_buf)); z_buf[sizeof(z_buf)-1] = '\0'; zb_string = z_buf; while (*zb_string) { *zb_string = tolower((unsigned char)(*zb_string)); zb_string++; } return z_buf; } void zephyr_print(netdissect_options *ndo, const u_char *cp, int length) { struct z_packet z; const char *parse = (const char *) cp; int parselen = length; const char *s; int lose = 0; /* squelch compiler warnings */ z.kind = 0; z.class = 0; z.inst = 0; z.opcode = 0; z.sender = 0; z.recipient = 0; #define PARSE_STRING \ s = parse_field(ndo, &parse, &parselen); \ if (!s) lose = 1; #define PARSE_FIELD_INT(field) \ PARSE_STRING \ if (!lose) field = strtol(s, 0, 16); #define PARSE_FIELD_STR(field) \ PARSE_STRING \ if (!lose) field = s; PARSE_FIELD_STR(z.version); if (lose) return; if (strncmp(z.version, "ZEPH", 4)) return; PARSE_FIELD_INT(z.numfields); PARSE_FIELD_INT(z.kind); PARSE_FIELD_STR(z.uid); PARSE_FIELD_INT(z.port); PARSE_FIELD_INT(z.auth); PARSE_FIELD_INT(z.authlen); PARSE_FIELD_STR(z.authdata); PARSE_FIELD_STR(z.class); PARSE_FIELD_STR(z.inst); PARSE_FIELD_STR(z.opcode); PARSE_FIELD_STR(z.sender); PARSE_FIELD_STR(z.recipient); PARSE_FIELD_STR(z.format); PARSE_FIELD_INT(z.cksum); PARSE_FIELD_INT(z.multi); PARSE_FIELD_STR(z.multi_uid); if (lose) { ND_PRINT((ndo, " [|zephyr] (%d)", length)); return; } ND_PRINT((ndo, " zephyr")); if (strncmp(z.version+4, "0.2", 3)) { ND_PRINT((ndo, " v%s", z.version+4)); return; } ND_PRINT((ndo, " %s", tok2str(z_types, "type %d", z.kind))); if (z.kind == Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *ackdata = NULL; PARSE_FIELD_STR(ackdata); if (!lose && strcmp(ackdata, "SENT")) ND_PRINT((ndo, "/%s", str_to_lower(ackdata))); } if (*z.sender) ND_PRINT((ndo, " %s", z.sender)); if (!strcmp(z.class, "USER_LOCATE")) { if (!strcmp(z.opcode, "USER_HIDE")) ND_PRINT((ndo, " hide")); else if (!strcmp(z.opcode, "USER_UNHIDE")) ND_PRINT((ndo, " unhide")); else ND_PRINT((ndo, " locate %s", z.inst)); return; } if (!strcmp(z.class, "ZEPHYR_ADMIN")) { ND_PRINT((ndo, " zephyr-admin %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "ZEPHYR_CTL")) { if (!strcmp(z.inst, "CLIENT")) { if (!strcmp(z.opcode, "SUBSCRIBE") || !strcmp(z.opcode, "SUBSCRIBE_NODEFS") || !strcmp(z.opcode, "UNSUBSCRIBE")) { ND_PRINT((ndo, " %ssub%s", strcmp(z.opcode, "SUBSCRIBE") ? "un" : "", strcmp(z.opcode, "SUBSCRIBE_NODEFS") ? "" : "-nodefs")); if (z.kind != Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *c = NULL, *i = NULL, *r = NULL; PARSE_FIELD_STR(c); PARSE_FIELD_STR(i); PARSE_FIELD_STR(r); if (!lose) ND_PRINT((ndo, " %s", z_triple(c, i, r))); } return; } if (!strcmp(z.opcode, "GIMME")) { ND_PRINT((ndo, " ret")); return; } if (!strcmp(z.opcode, "GIMMEDEFS")) { ND_PRINT((ndo, " gimme-defs")); return; } if (!strcmp(z.opcode, "CLEARSUB")) { ND_PRINT((ndo, " clear-subs")); return; } ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "HM")) { ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "REALM")) { if (!strcmp(z.opcode, "ADD_SUBSCRIBE")) ND_PRINT((ndo, " realm add-subs")); if (!strcmp(z.opcode, "REQ_SUBSCRIBE")) ND_PRINT((ndo, " realm req-subs")); if (!strcmp(z.opcode, "RLM_SUBSCRIBE")) ND_PRINT((ndo, " realm rlm-sub")); if (!strcmp(z.opcode, "RLM_UNSUBSCRIBE")) ND_PRINT((ndo, " realm rlm-unsub")); return; } } if (!strcmp(z.class, "HM_CTL")) { ND_PRINT((ndo, " hm_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "HM_STAT")) { if (!strcmp(z.inst, "HMST_CLIENT") && !strcmp(z.opcode, "GIMMESTATS")) { ND_PRINT((ndo, " get-client-stats")); return; } } if (!strcmp(z.class, "WG_CTL")) { ND_PRINT((ndo, " wg_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "LOGIN")) { if (!strcmp(z.opcode, "USER_FLUSH")) { ND_PRINT((ndo, " flush_locs")); return; } if (!strcmp(z.opcode, "NONE") || !strcmp(z.opcode, "OPSTAFF") || !strcmp(z.opcode, "REALM-VISIBLE") || !strcmp(z.opcode, "REALM-ANNOUNCED") || !strcmp(z.opcode, "NET-VISIBLE") || !strcmp(z.opcode, "NET-ANNOUNCED")) { ND_PRINT((ndo, " set-exposure %s", str_to_lower(z.opcode))); return; } } if (!*z.recipient) z.recipient = "*"; ND_PRINT((ndo, " to %s", z_triple(z.class, z.inst, z.recipient))); if (*z.opcode) ND_PRINT((ndo, " op %s", z.opcode)); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2648_3
crossvul-cpp_data_good_4857_2
/* $Id$ */ /* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * 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. */ /* * TIFF Library. * * Strip-organized Image Support Routines. */ #include "tiffiop.h" /* * Compute which strip a (row,sample) value is in. */ uint32 TIFFComputeStrip(TIFF* tif, uint32 row, uint16 sample) { static const char module[] = "TIFFComputeStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 strip; strip = row / td->td_rowsperstrip; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (0); } strip += (uint32)sample*td->td_stripsperimage; } return (strip); } /* * Compute how many strips are in an image. */ uint32 TIFFNumberOfStrips(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; uint32 nstrips; nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 : TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip)); if (td->td_planarconfig == PLANARCONFIG_SEPARATE) nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel, "TIFFNumberOfStrips"); return (nstrips); } /* * Compute the # bytes in a variable height, row-aligned strip. */ uint64 TIFFVStripSize64(TIFF* tif, uint32 nrows) { static const char module[] = "TIFFVStripSize64"; TIFFDirectory *td = &tif->tif_dir; if (nrows==(uint32)(-1)) nrows=td->td_imagelength; if ((td->td_planarconfig==PLANARCONFIG_CONTIG)&& (td->td_photometric == PHOTOMETRIC_YCBCR)&& (!isUpSampled(tif))) { /* * Packed YCbCr data contain one Cb+Cr for every * HorizontalSampling*VerticalSampling Y values. * Must also roundup width and height when calculating * since images that are not a multiple of the * horizontal/vertical subsampling area include * YCbCr data for the extended image. */ uint16 ycbcrsubsampling[2]; uint16 samplingblock_samples; uint32 samplingblocks_hor; uint32 samplingblocks_ver; uint64 samplingrow_samples; uint64 samplingrow_size; if(td->td_samplesperpixel!=3) { TIFFErrorExt(tif->tif_clientdata,module, "Invalid td_samplesperpixel value"); return 0; } TIFFGetFieldDefaulted(tif,TIFFTAG_YCBCRSUBSAMPLING,ycbcrsubsampling+0, ycbcrsubsampling+1); if ((ycbcrsubsampling[0] != 1 && ycbcrsubsampling[0] != 2 && ycbcrsubsampling[0] != 4) ||(ycbcrsubsampling[1] != 1 && ycbcrsubsampling[1] != 2 && ycbcrsubsampling[1] != 4)) { TIFFErrorExt(tif->tif_clientdata,module, "Invalid YCbCr subsampling (%dx%d)", ycbcrsubsampling[0], ycbcrsubsampling[1] ); return 0; } samplingblock_samples=ycbcrsubsampling[0]*ycbcrsubsampling[1]+2; samplingblocks_hor=TIFFhowmany_32(td->td_imagewidth,ycbcrsubsampling[0]); samplingblocks_ver=TIFFhowmany_32(nrows,ycbcrsubsampling[1]); samplingrow_samples=_TIFFMultiply64(tif,samplingblocks_hor,samplingblock_samples,module); samplingrow_size=TIFFhowmany8_64(_TIFFMultiply64(tif,samplingrow_samples,td->td_bitspersample,module)); return(_TIFFMultiply64(tif,samplingrow_size,samplingblocks_ver,module)); } else return(_TIFFMultiply64(tif,nrows,TIFFScanlineSize64(tif),module)); } tmsize_t TIFFVStripSize(TIFF* tif, uint32 nrows) { static const char module[] = "TIFFVStripSize"; uint64 m; tmsize_t n; m=TIFFVStripSize64(tif,nrows); n=(tmsize_t)m; if ((uint64)n!=m) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); n=0; } return(n); } /* * Compute the # bytes in a raw strip. */ uint64 TIFFRawStripSize64(TIFF* tif, uint32 strip) { static const char module[] = "TIFFRawStripSize64"; TIFFDirectory* td = &tif->tif_dir; uint64 bytecount = td->td_stripbytecount[strip]; if (bytecount == 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "%I64u: Invalid strip byte count, strip %lu", (unsigned __int64) bytecount, (unsigned long) strip); #else TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid strip byte count, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); #endif bytecount = (uint64) -1; } return bytecount; } tmsize_t TIFFRawStripSize(TIFF* tif, uint32 strip) { static const char module[] = "TIFFRawStripSize"; uint64 m; tmsize_t n; m=TIFFRawStripSize64(tif,strip); if (m==(uint64)(-1)) n=(tmsize_t)(-1); else { n=(tmsize_t)m; if ((uint64)n!=m) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); n=0; } } return(n); } /* * Compute the # bytes in a (row-aligned) strip. * * Note that if RowsPerStrip is larger than the * recorded ImageLength, then the strip size is * truncated to reflect the actual space required * to hold the strip. */ uint64 TIFFStripSize64(TIFF* tif) { TIFFDirectory* td = &tif->tif_dir; uint32 rps = td->td_rowsperstrip; if (rps > td->td_imagelength) rps = td->td_imagelength; return (TIFFVStripSize64(tif, rps)); } tmsize_t TIFFStripSize(TIFF* tif) { static const char module[] = "TIFFStripSize"; uint64 m; tmsize_t n; m=TIFFStripSize64(tif); n=(tmsize_t)m; if ((uint64)n!=m) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); n=0; } return(n); } /* * Compute a default strip size based on the image * characteristics and a requested value. If the * request is <1 then we choose a strip size according * to certain heuristics. */ uint32 TIFFDefaultStripSize(TIFF* tif, uint32 request) { return (*tif->tif_defstripsize)(tif, request); } uint32 _TIFFDefaultStripSize(TIFF* tif, uint32 s) { if ((int32) s < 1) { /* * If RowsPerStrip is unspecified, try to break the * image up into strips that are approximately * STRIP_SIZE_DEFAULT bytes long. */ uint64 scanlinesize; uint64 rows; scanlinesize=TIFFScanlineSize64(tif); if (scanlinesize==0) scanlinesize=1; rows=(uint64)STRIP_SIZE_DEFAULT/scanlinesize; if (rows==0) rows=1; else if (rows>0xFFFFFFFF) rows=0xFFFFFFFF; s=(uint32)rows; } return (s); } /* * Return the number of bytes to read/write in a call to * one of the scanline-oriented i/o routines. Note that * this number may be 1/samples-per-pixel if data is * stored as separate planes. * The ScanlineSize in case of YCbCrSubsampling is defined as the * strip size divided by the strip height, i.e. the size of a pack of vertical * subsampling lines divided by vertical subsampling. It should thus make * sense when multiplied by a multiple of vertical subsampling. */ uint64 TIFFScanlineSize64(TIFF* tif) { static const char module[] = "TIFFScanlineSize64"; TIFFDirectory *td = &tif->tif_dir; uint64 scanline_size; if (td->td_planarconfig==PLANARCONFIG_CONTIG) { if ((td->td_photometric==PHOTOMETRIC_YCBCR)&& (td->td_samplesperpixel==3)&& (!isUpSampled(tif))) { uint16 ycbcrsubsampling[2]; uint16 samplingblock_samples; uint32 samplingblocks_hor; uint64 samplingrow_samples; uint64 samplingrow_size; if(td->td_samplesperpixel!=3) { TIFFErrorExt(tif->tif_clientdata,module, "Invalid td_samplesperpixel value"); return 0; } TIFFGetFieldDefaulted(tif,TIFFTAG_YCBCRSUBSAMPLING, ycbcrsubsampling+0, ycbcrsubsampling+1); if (((ycbcrsubsampling[0]!=1)&&(ycbcrsubsampling[0]!=2)&&(ycbcrsubsampling[0]!=4)) || ((ycbcrsubsampling[1]!=1)&&(ycbcrsubsampling[1]!=2)&&(ycbcrsubsampling[1]!=4))) { TIFFErrorExt(tif->tif_clientdata,module, "Invalid YCbCr subsampling"); return 0; } samplingblock_samples = ycbcrsubsampling[0]*ycbcrsubsampling[1]+2; samplingblocks_hor = TIFFhowmany_32(td->td_imagewidth,ycbcrsubsampling[0]); samplingrow_samples = _TIFFMultiply64(tif,samplingblocks_hor,samplingblock_samples,module); samplingrow_size = TIFFhowmany_64(_TIFFMultiply64(tif,samplingrow_samples,td->td_bitspersample,module),8); scanline_size = (samplingrow_size/ycbcrsubsampling[1]); } else { uint64 scanline_samples; scanline_samples=_TIFFMultiply64(tif,td->td_imagewidth,td->td_samplesperpixel,module); scanline_size=TIFFhowmany_64(_TIFFMultiply64(tif,scanline_samples,td->td_bitspersample,module),8); } } else { scanline_size=TIFFhowmany_64(_TIFFMultiply64(tif,td->td_imagewidth,td->td_bitspersample,module),8); } if (scanline_size == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Computed scanline size is zero"); return 0; } return(scanline_size); } tmsize_t TIFFScanlineSize(TIFF* tif) { static const char module[] = "TIFFScanlineSize"; uint64 m; tmsize_t n; m=TIFFScanlineSize64(tif); n=(tmsize_t)m; if ((uint64)n!=m) { TIFFErrorExt(tif->tif_clientdata,module,"Integer arithmetic overflow"); n=0; } return(n); } /* * Return the number of bytes required to store a complete * decoded and packed raster scanline (as opposed to the * I/O size returned by TIFFScanlineSize which may be less * if data is store as separate planes). */ uint64 TIFFRasterScanlineSize64(TIFF* tif) { static const char module[] = "TIFFRasterScanlineSize64"; TIFFDirectory *td = &tif->tif_dir; uint64 scanline; scanline = _TIFFMultiply64(tif, td->td_bitspersample, td->td_imagewidth, module); if (td->td_planarconfig == PLANARCONFIG_CONTIG) { scanline = _TIFFMultiply64(tif, scanline, td->td_samplesperpixel, module); return (TIFFhowmany8_64(scanline)); } else return (_TIFFMultiply64(tif, TIFFhowmany8_64(scanline), td->td_samplesperpixel, module)); } tmsize_t TIFFRasterScanlineSize(TIFF* tif) { static const char module[] = "TIFFRasterScanlineSize"; uint64 m; tmsize_t n; m=TIFFRasterScanlineSize64(tif); n=(tmsize_t)m; if ((uint64)n!=m) { TIFFErrorExt(tif->tif_clientdata,module,"Integer arithmetic overflow"); n=0; } return(n); } /* 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-125/c/good_4857_2
crossvul-cpp_data_good_5338_0
/* * HID support for Linux * * 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-2012 Jiri Kosina */ /* * 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/module.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <asm/unaligned.h> #include <asm/byteorder.h> #include <linux/input.h> #include <linux/wait.h> #include <linux/vmalloc.h> #include <linux/sched.h> #include <linux/semaphore.h> #include <linux/hid.h> #include <linux/hiddev.h> #include <linux/hid-debug.h> #include <linux/hidraw.h> #include "hid-ids.h" /* * Version Information */ #define DRIVER_DESC "HID core driver" #define DRIVER_LICENSE "GPL" int hid_debug = 0; module_param_named(debug, hid_debug, int, 0600); MODULE_PARM_DESC(debug, "toggle HID debugging messages"); EXPORT_SYMBOL_GPL(hid_debug); static int hid_ignore_special_drivers = 0; module_param_named(ignore_special_drivers, hid_ignore_special_drivers, int, 0600); MODULE_PARM_DESC(ignore_special_drivers, "Ignore any special drivers and handle all devices by generic driver"); /* * Register a new report for a device. */ struct hid_report *hid_register_report(struct hid_device *device, unsigned type, unsigned id) { struct hid_report_enum *report_enum = device->report_enum + type; struct hid_report *report; if (id >= HID_MAX_IDS) return NULL; if (report_enum->report_id_hash[id]) return report_enum->report_id_hash[id]; report = kzalloc(sizeof(struct hid_report), GFP_KERNEL); if (!report) return NULL; if (id != 0) report_enum->numbered = 1; report->id = id; report->type = type; report->size = 0; report->device = device; report_enum->report_id_hash[id] = report; list_add_tail(&report->list, &report_enum->report_list); return report; } EXPORT_SYMBOL_GPL(hid_register_report); /* * Register a new field for this report. */ static struct hid_field *hid_register_field(struct hid_report *report, unsigned usages, unsigned values) { struct hid_field *field; if (report->maxfield == HID_MAX_FIELDS) { hid_err(report->device, "too many fields in report\n"); return NULL; } field = kzalloc((sizeof(struct hid_field) + usages * sizeof(struct hid_usage) + values * sizeof(unsigned)), GFP_KERNEL); if (!field) return NULL; field->index = report->maxfield++; report->field[field->index] = field; field->usage = (struct hid_usage *)(field + 1); field->value = (s32 *)(field->usage + usages); field->report = report; return field; } /* * Open a collection. The type/usage is pushed on the stack. */ static int open_collection(struct hid_parser *parser, unsigned type) { struct hid_collection *collection; unsigned usage; usage = parser->local.usage[0]; if (parser->collection_stack_ptr == HID_COLLECTION_STACK_SIZE) { hid_err(parser->device, "collection stack overflow\n"); return -EINVAL; } if (parser->device->maxcollection == parser->device->collection_size) { collection = kmalloc(sizeof(struct hid_collection) * parser->device->collection_size * 2, GFP_KERNEL); if (collection == NULL) { hid_err(parser->device, "failed to reallocate collection array\n"); return -ENOMEM; } memcpy(collection, parser->device->collection, sizeof(struct hid_collection) * parser->device->collection_size); memset(collection + parser->device->collection_size, 0, sizeof(struct hid_collection) * parser->device->collection_size); kfree(parser->device->collection); parser->device->collection = collection; parser->device->collection_size *= 2; } parser->collection_stack[parser->collection_stack_ptr++] = parser->device->maxcollection; collection = parser->device->collection + parser->device->maxcollection++; collection->type = type; collection->usage = usage; collection->level = parser->collection_stack_ptr - 1; if (type == HID_COLLECTION_APPLICATION) parser->device->maxapplication++; return 0; } /* * Close a collection. */ static int close_collection(struct hid_parser *parser) { if (!parser->collection_stack_ptr) { hid_err(parser->device, "collection stack underflow\n"); return -EINVAL; } parser->collection_stack_ptr--; return 0; } /* * Climb up the stack, search for the specified collection type * and return the usage. */ static unsigned hid_lookup_collection(struct hid_parser *parser, unsigned type) { struct hid_collection *collection = parser->device->collection; int n; for (n = parser->collection_stack_ptr - 1; n >= 0; n--) { unsigned index = parser->collection_stack[n]; if (collection[index].type == type) return collection[index].usage; } return 0; /* we know nothing about this usage type */ } /* * Add a usage to the temporary parser table. */ static int hid_add_usage(struct hid_parser *parser, unsigned usage) { if (parser->local.usage_index >= HID_MAX_USAGES) { hid_err(parser->device, "usage index exceeded\n"); return -1; } parser->local.usage[parser->local.usage_index] = usage; parser->local.collection_index[parser->local.usage_index] = parser->collection_stack_ptr ? parser->collection_stack[parser->collection_stack_ptr - 1] : 0; parser->local.usage_index++; return 0; } /* * Register a new field for this report. */ static int hid_add_field(struct hid_parser *parser, unsigned report_type, unsigned flags) { struct hid_report *report; struct hid_field *field; unsigned usages; unsigned offset; unsigned i; report = hid_register_report(parser->device, report_type, parser->global.report_id); if (!report) { hid_err(parser->device, "hid_register_report failed\n"); return -1; } /* Handle both signed and unsigned cases properly */ if ((parser->global.logical_minimum < 0 && parser->global.logical_maximum < parser->global.logical_minimum) || (parser->global.logical_minimum >= 0 && (__u32)parser->global.logical_maximum < (__u32)parser->global.logical_minimum)) { dbg_hid("logical range invalid 0x%x 0x%x\n", parser->global.logical_minimum, parser->global.logical_maximum); return -1; } offset = report->size; report->size += parser->global.report_size * parser->global.report_count; if (!parser->local.usage_index) /* Ignore padding fields */ return 0; usages = max_t(unsigned, parser->local.usage_index, parser->global.report_count); field = hid_register_field(report, usages, parser->global.report_count); if (!field) return 0; field->physical = hid_lookup_collection(parser, HID_COLLECTION_PHYSICAL); field->logical = hid_lookup_collection(parser, HID_COLLECTION_LOGICAL); field->application = hid_lookup_collection(parser, HID_COLLECTION_APPLICATION); for (i = 0; i < usages; i++) { unsigned j = i; /* Duplicate the last usage we parsed if we have excess values */ if (i >= parser->local.usage_index) j = parser->local.usage_index - 1; field->usage[i].hid = parser->local.usage[j]; field->usage[i].collection_index = parser->local.collection_index[j]; field->usage[i].usage_index = i; } field->maxusage = usages; field->flags = flags; field->report_offset = offset; field->report_type = report_type; field->report_size = parser->global.report_size; field->report_count = parser->global.report_count; field->logical_minimum = parser->global.logical_minimum; field->logical_maximum = parser->global.logical_maximum; field->physical_minimum = parser->global.physical_minimum; field->physical_maximum = parser->global.physical_maximum; field->unit_exponent = parser->global.unit_exponent; field->unit = parser->global.unit; return 0; } /* * Read data value from item. */ static u32 item_udata(struct hid_item *item) { switch (item->size) { case 1: return item->data.u8; case 2: return item->data.u16; case 4: return item->data.u32; } return 0; } static s32 item_sdata(struct hid_item *item) { switch (item->size) { case 1: return item->data.s8; case 2: return item->data.s16; case 4: return item->data.s32; } return 0; } /* * Process a global item. */ static int hid_parser_global(struct hid_parser *parser, struct hid_item *item) { __s32 raw_value; switch (item->tag) { case HID_GLOBAL_ITEM_TAG_PUSH: if (parser->global_stack_ptr == HID_GLOBAL_STACK_SIZE) { hid_err(parser->device, "global environment stack overflow\n"); return -1; } memcpy(parser->global_stack + parser->global_stack_ptr++, &parser->global, sizeof(struct hid_global)); return 0; case HID_GLOBAL_ITEM_TAG_POP: if (!parser->global_stack_ptr) { hid_err(parser->device, "global environment stack underflow\n"); return -1; } memcpy(&parser->global, parser->global_stack + --parser->global_stack_ptr, sizeof(struct hid_global)); return 0; case HID_GLOBAL_ITEM_TAG_USAGE_PAGE: parser->global.usage_page = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_LOGICAL_MINIMUM: parser->global.logical_minimum = item_sdata(item); return 0; case HID_GLOBAL_ITEM_TAG_LOGICAL_MAXIMUM: if (parser->global.logical_minimum < 0) parser->global.logical_maximum = item_sdata(item); else parser->global.logical_maximum = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_PHYSICAL_MINIMUM: parser->global.physical_minimum = item_sdata(item); return 0; case HID_GLOBAL_ITEM_TAG_PHYSICAL_MAXIMUM: if (parser->global.physical_minimum < 0) parser->global.physical_maximum = item_sdata(item); else parser->global.physical_maximum = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_UNIT_EXPONENT: /* Many devices provide unit exponent as a two's complement * nibble due to the common misunderstanding of HID * specification 1.11, 6.2.2.7 Global Items. Attempt to handle * both this and the standard encoding. */ raw_value = item_sdata(item); if (!(raw_value & 0xfffffff0)) parser->global.unit_exponent = hid_snto32(raw_value, 4); else parser->global.unit_exponent = raw_value; return 0; case HID_GLOBAL_ITEM_TAG_UNIT: parser->global.unit = item_udata(item); return 0; case HID_GLOBAL_ITEM_TAG_REPORT_SIZE: parser->global.report_size = item_udata(item); if (parser->global.report_size > 128) { hid_err(parser->device, "invalid report_size %d\n", parser->global.report_size); return -1; } return 0; case HID_GLOBAL_ITEM_TAG_REPORT_COUNT: parser->global.report_count = item_udata(item); if (parser->global.report_count > HID_MAX_USAGES) { hid_err(parser->device, "invalid report_count %d\n", parser->global.report_count); return -1; } return 0; case HID_GLOBAL_ITEM_TAG_REPORT_ID: parser->global.report_id = item_udata(item); if (parser->global.report_id == 0 || parser->global.report_id >= HID_MAX_IDS) { hid_err(parser->device, "report_id %u is invalid\n", parser->global.report_id); return -1; } return 0; default: hid_err(parser->device, "unknown global tag 0x%x\n", item->tag); return -1; } } /* * Process a local item. */ static int hid_parser_local(struct hid_parser *parser, struct hid_item *item) { __u32 data; unsigned n; __u32 count; data = item_udata(item); switch (item->tag) { case HID_LOCAL_ITEM_TAG_DELIMITER: if (data) { /* * We treat items before the first delimiter * as global to all usage sets (branch 0). * In the moment we process only these global * items and the first delimiter set. */ if (parser->local.delimiter_depth != 0) { hid_err(parser->device, "nested delimiters\n"); return -1; } parser->local.delimiter_depth++; parser->local.delimiter_branch++; } else { if (parser->local.delimiter_depth < 1) { hid_err(parser->device, "bogus close delimiter\n"); return -1; } parser->local.delimiter_depth--; } return 0; case HID_LOCAL_ITEM_TAG_USAGE: if (parser->local.delimiter_branch > 1) { dbg_hid("alternative usage ignored\n"); return 0; } if (item->size <= 2) data = (parser->global.usage_page << 16) + data; return hid_add_usage(parser, data); case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM: if (parser->local.delimiter_branch > 1) { dbg_hid("alternative usage ignored\n"); return 0; } if (item->size <= 2) data = (parser->global.usage_page << 16) + data; parser->local.usage_minimum = data; return 0; case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM: if (parser->local.delimiter_branch > 1) { dbg_hid("alternative usage ignored\n"); return 0; } if (item->size <= 2) data = (parser->global.usage_page << 16) + data; count = data - parser->local.usage_minimum; if (count + parser->local.usage_index >= HID_MAX_USAGES) { /* * We do not warn if the name is not set, we are * actually pre-scanning the device. */ if (dev_name(&parser->device->dev)) hid_warn(parser->device, "ignoring exceeding usage max\n"); data = HID_MAX_USAGES - parser->local.usage_index + parser->local.usage_minimum - 1; if (data <= 0) { hid_err(parser->device, "no more usage index available\n"); return -1; } } for (n = parser->local.usage_minimum; n <= data; n++) if (hid_add_usage(parser, n)) { dbg_hid("hid_add_usage failed\n"); return -1; } return 0; default: dbg_hid("unknown local item tag 0x%x\n", item->tag); return 0; } return 0; } /* * Process a main item. */ static int hid_parser_main(struct hid_parser *parser, struct hid_item *item) { __u32 data; int ret; data = item_udata(item); switch (item->tag) { case HID_MAIN_ITEM_TAG_BEGIN_COLLECTION: ret = open_collection(parser, data & 0xff); break; case HID_MAIN_ITEM_TAG_END_COLLECTION: ret = close_collection(parser); break; case HID_MAIN_ITEM_TAG_INPUT: ret = hid_add_field(parser, HID_INPUT_REPORT, data); break; case HID_MAIN_ITEM_TAG_OUTPUT: ret = hid_add_field(parser, HID_OUTPUT_REPORT, data); break; case HID_MAIN_ITEM_TAG_FEATURE: ret = hid_add_field(parser, HID_FEATURE_REPORT, data); break; default: hid_err(parser->device, "unknown main item tag 0x%x\n", item->tag); ret = 0; } memset(&parser->local, 0, sizeof(parser->local)); /* Reset the local parser environment */ return ret; } /* * Process a reserved item. */ static int hid_parser_reserved(struct hid_parser *parser, struct hid_item *item) { dbg_hid("reserved item type, tag 0x%x\n", item->tag); return 0; } /* * Free a report and all registered fields. The field->usage and * field->value table's are allocated behind the field, so we need * only to free(field) itself. */ static void hid_free_report(struct hid_report *report) { unsigned n; for (n = 0; n < report->maxfield; n++) kfree(report->field[n]); kfree(report); } /* * Close report. This function returns the device * state to the point prior to hid_open_report(). */ static void hid_close_report(struct hid_device *device) { unsigned i, j; for (i = 0; i < HID_REPORT_TYPES; i++) { struct hid_report_enum *report_enum = device->report_enum + i; for (j = 0; j < HID_MAX_IDS; j++) { struct hid_report *report = report_enum->report_id_hash[j]; if (report) hid_free_report(report); } memset(report_enum, 0, sizeof(*report_enum)); INIT_LIST_HEAD(&report_enum->report_list); } kfree(device->rdesc); device->rdesc = NULL; device->rsize = 0; kfree(device->collection); device->collection = NULL; device->collection_size = 0; device->maxcollection = 0; device->maxapplication = 0; device->status &= ~HID_STAT_PARSED; } /* * Free a device structure, all reports, and all fields. */ static void hid_device_release(struct device *dev) { struct hid_device *hid = to_hid_device(dev); hid_close_report(hid); kfree(hid->dev_rdesc); kfree(hid); } /* * Fetch a report description item from the data stream. We support long * items, though they are not used yet. */ static u8 *fetch_item(__u8 *start, __u8 *end, struct hid_item *item) { u8 b; if ((end - start) <= 0) return NULL; b = *start++; item->type = (b >> 2) & 3; item->tag = (b >> 4) & 15; if (item->tag == HID_ITEM_TAG_LONG) { item->format = HID_ITEM_FORMAT_LONG; if ((end - start) < 2) return NULL; item->size = *start++; item->tag = *start++; if ((end - start) < item->size) return NULL; item->data.longdata = start; start += item->size; return start; } item->format = HID_ITEM_FORMAT_SHORT; item->size = b & 3; switch (item->size) { case 0: return start; case 1: if ((end - start) < 1) return NULL; item->data.u8 = *start++; return start; case 2: if ((end - start) < 2) return NULL; item->data.u16 = get_unaligned_le16(start); start = (__u8 *)((__le16 *)start + 1); return start; case 3: item->size++; if ((end - start) < 4) return NULL; item->data.u32 = get_unaligned_le32(start); start = (__u8 *)((__le32 *)start + 1); return start; } return NULL; } static void hid_scan_input_usage(struct hid_parser *parser, u32 usage) { struct hid_device *hid = parser->device; if (usage == HID_DG_CONTACTID) hid->group = HID_GROUP_MULTITOUCH; } static void hid_scan_feature_usage(struct hid_parser *parser, u32 usage) { if (usage == 0xff0000c5 && parser->global.report_count == 256 && parser->global.report_size == 8) parser->scan_flags |= HID_SCAN_FLAG_MT_WIN_8; } static void hid_scan_collection(struct hid_parser *parser, unsigned type) { struct hid_device *hid = parser->device; int i; if (((parser->global.usage_page << 16) == HID_UP_SENSOR) && type == HID_COLLECTION_PHYSICAL) hid->group = HID_GROUP_SENSOR_HUB; if (hid->vendor == USB_VENDOR_ID_MICROSOFT && (hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3 || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_2 || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_JP || hid->product == USB_DEVICE_ID_MS_TYPE_COVER_3 || hid->product == USB_DEVICE_ID_MS_POWER_COVER) && hid->group == HID_GROUP_MULTITOUCH) hid->group = HID_GROUP_GENERIC; if ((parser->global.usage_page << 16) == HID_UP_GENDESK) for (i = 0; i < parser->local.usage_index; i++) if (parser->local.usage[i] == HID_GD_POINTER) parser->scan_flags |= HID_SCAN_FLAG_GD_POINTER; if ((parser->global.usage_page << 16) >= HID_UP_MSVENDOR) parser->scan_flags |= HID_SCAN_FLAG_VENDOR_SPECIFIC; } static int hid_scan_main(struct hid_parser *parser, struct hid_item *item) { __u32 data; int i; data = item_udata(item); switch (item->tag) { case HID_MAIN_ITEM_TAG_BEGIN_COLLECTION: hid_scan_collection(parser, data & 0xff); break; case HID_MAIN_ITEM_TAG_END_COLLECTION: break; case HID_MAIN_ITEM_TAG_INPUT: /* ignore constant inputs, they will be ignored by hid-input */ if (data & HID_MAIN_ITEM_CONSTANT) break; for (i = 0; i < parser->local.usage_index; i++) hid_scan_input_usage(parser, parser->local.usage[i]); break; case HID_MAIN_ITEM_TAG_OUTPUT: break; case HID_MAIN_ITEM_TAG_FEATURE: for (i = 0; i < parser->local.usage_index; i++) hid_scan_feature_usage(parser, parser->local.usage[i]); break; } /* Reset the local parser environment */ memset(&parser->local, 0, sizeof(parser->local)); return 0; } /* * Scan a report descriptor before the device is added to the bus. * Sets device groups and other properties that determine what driver * to load. */ static int hid_scan_report(struct hid_device *hid) { struct hid_parser *parser; struct hid_item item; __u8 *start = hid->dev_rdesc; __u8 *end = start + hid->dev_rsize; static int (*dispatch_type[])(struct hid_parser *parser, struct hid_item *item) = { hid_scan_main, hid_parser_global, hid_parser_local, hid_parser_reserved }; parser = vzalloc(sizeof(struct hid_parser)); if (!parser) return -ENOMEM; parser->device = hid; hid->group = HID_GROUP_GENERIC; /* * The parsing is simpler than the one in hid_open_report() as we should * be robust against hid errors. Those errors will be raised by * hid_open_report() anyway. */ while ((start = fetch_item(start, end, &item)) != NULL) dispatch_type[item.type](parser, &item); /* * Handle special flags set during scanning. */ if ((parser->scan_flags & HID_SCAN_FLAG_MT_WIN_8) && (hid->group == HID_GROUP_MULTITOUCH)) hid->group = HID_GROUP_MULTITOUCH_WIN_8; /* * Vendor specific handlings */ switch (hid->vendor) { case USB_VENDOR_ID_WACOM: hid->group = HID_GROUP_WACOM; break; case USB_VENDOR_ID_SYNAPTICS: if (hid->group == HID_GROUP_GENERIC) if ((parser->scan_flags & HID_SCAN_FLAG_VENDOR_SPECIFIC) && (parser->scan_flags & HID_SCAN_FLAG_GD_POINTER)) /* * hid-rmi should take care of them, * not hid-generic */ hid->group = HID_GROUP_RMI; break; } vfree(parser); return 0; } /** * hid_parse_report - parse device report * * @device: hid device * @start: report start * @size: report size * * Allocate the device report as read by the bus driver. This function should * only be called from parse() in ll drivers. */ int hid_parse_report(struct hid_device *hid, __u8 *start, unsigned size) { hid->dev_rdesc = kmemdup(start, size, GFP_KERNEL); if (!hid->dev_rdesc) return -ENOMEM; hid->dev_rsize = size; return 0; } EXPORT_SYMBOL_GPL(hid_parse_report); static const char * const hid_report_names[] = { "HID_INPUT_REPORT", "HID_OUTPUT_REPORT", "HID_FEATURE_REPORT", }; /** * hid_validate_values - validate existing device report's value indexes * * @device: hid device * @type: which report type to examine * @id: which report ID to examine (0 for first) * @field_index: which report field to examine * @report_counts: expected number of values * * Validate the number of values in a given field of a given report, after * parsing. */ struct hid_report *hid_validate_values(struct hid_device *hid, unsigned int type, unsigned int id, unsigned int field_index, unsigned int report_counts) { struct hid_report *report; if (type > HID_FEATURE_REPORT) { hid_err(hid, "invalid HID report type %u\n", type); return NULL; } if (id >= HID_MAX_IDS) { hid_err(hid, "invalid HID report id %u\n", id); return NULL; } /* * Explicitly not using hid_get_report() here since it depends on * ->numbered being checked, which may not always be the case when * drivers go to access report values. */ if (id == 0) { /* * Validating on id 0 means we should examine the first * report in the list. */ report = list_entry( hid->report_enum[type].report_list.next, struct hid_report, list); } else { report = hid->report_enum[type].report_id_hash[id]; } if (!report) { hid_err(hid, "missing %s %u\n", hid_report_names[type], id); return NULL; } if (report->maxfield <= field_index) { hid_err(hid, "not enough fields in %s %u\n", hid_report_names[type], id); return NULL; } if (report->field[field_index]->report_count < report_counts) { hid_err(hid, "not enough values in %s %u field %u\n", hid_report_names[type], id, field_index); return NULL; } return report; } EXPORT_SYMBOL_GPL(hid_validate_values); /** * hid_open_report - open a driver-specific device report * * @device: hid device * * Parse a report description into a hid_device structure. Reports are * enumerated, fields are attached to these reports. * 0 returned on success, otherwise nonzero error value. * * This function (or the equivalent hid_parse() macro) should only be * called from probe() in drivers, before starting the device. */ int hid_open_report(struct hid_device *device) { struct hid_parser *parser; struct hid_item item; unsigned int size; __u8 *start; __u8 *buf; __u8 *end; int ret; static int (*dispatch_type[])(struct hid_parser *parser, struct hid_item *item) = { hid_parser_main, hid_parser_global, hid_parser_local, hid_parser_reserved }; if (WARN_ON(device->status & HID_STAT_PARSED)) return -EBUSY; start = device->dev_rdesc; if (WARN_ON(!start)) return -ENODEV; size = device->dev_rsize; buf = kmemdup(start, size, GFP_KERNEL); if (buf == NULL) return -ENOMEM; if (device->driver->report_fixup) start = device->driver->report_fixup(device, buf, &size); else start = buf; start = kmemdup(start, size, GFP_KERNEL); kfree(buf); if (start == NULL) return -ENOMEM; device->rdesc = start; device->rsize = size; parser = vzalloc(sizeof(struct hid_parser)); if (!parser) { ret = -ENOMEM; goto err; } parser->device = device; end = start + size; device->collection = kcalloc(HID_DEFAULT_NUM_COLLECTIONS, sizeof(struct hid_collection), GFP_KERNEL); if (!device->collection) { ret = -ENOMEM; goto err; } device->collection_size = HID_DEFAULT_NUM_COLLECTIONS; ret = -EINVAL; while ((start = fetch_item(start, end, &item)) != NULL) { if (item.format != HID_ITEM_FORMAT_SHORT) { hid_err(device, "unexpected long global item\n"); goto err; } if (dispatch_type[item.type](parser, &item)) { hid_err(device, "item %u %u %u %u parsing failed\n", item.format, (unsigned)item.size, (unsigned)item.type, (unsigned)item.tag); goto err; } if (start == end) { if (parser->collection_stack_ptr) { hid_err(device, "unbalanced collection at end of report description\n"); goto err; } if (parser->local.delimiter_depth) { hid_err(device, "unbalanced delimiter at end of report description\n"); goto err; } vfree(parser); device->status |= HID_STAT_PARSED; return 0; } } hid_err(device, "item fetching failed at offset %d\n", (int)(end - start)); err: vfree(parser); hid_close_report(device); return ret; } EXPORT_SYMBOL_GPL(hid_open_report); /* * Convert a signed n-bit integer to signed 32-bit integer. Common * cases are done through the compiler, the screwed things has to be * done by hand. */ static s32 snto32(__u32 value, unsigned n) { switch (n) { case 8: return ((__s8)value); case 16: return ((__s16)value); case 32: return ((__s32)value); } return value & (1 << (n - 1)) ? value | (-1 << n) : value; } s32 hid_snto32(__u32 value, unsigned n) { return snto32(value, n); } EXPORT_SYMBOL_GPL(hid_snto32); /* * Convert a signed 32-bit integer to a signed n-bit integer. */ static u32 s32ton(__s32 value, unsigned n) { s32 a = value >> (n - 1); if (a && a != -1) return value < 0 ? 1 << (n - 1) : (1 << (n - 1)) - 1; return value & ((1 << n) - 1); } /* * Extract/implement a data field from/to a little endian report (bit array). * * Code sort-of follows HID spec: * http://www.usb.org/developers/hidpage/HID1_11.pdf * * While the USB HID spec allows unlimited length bit fields in "report * descriptors", most devices never use more than 16 bits. * One model of UPS is claimed to report "LINEV" as a 32-bit field. * Search linux-kernel and linux-usb-devel archives for "hid-core extract". */ static u32 __extract(u8 *report, unsigned offset, int n) { unsigned int idx = offset / 8; unsigned int bit_nr = 0; unsigned int bit_shift = offset % 8; int bits_to_copy = 8 - bit_shift; u32 value = 0; u32 mask = n < 32 ? (1U << n) - 1 : ~0U; while (n > 0) { value |= ((u32)report[idx] >> bit_shift) << bit_nr; n -= bits_to_copy; bit_nr += bits_to_copy; bits_to_copy = 8; bit_shift = 0; idx++; } return value & mask; } u32 hid_field_extract(const struct hid_device *hid, u8 *report, unsigned offset, unsigned n) { if (n > 32) { hid_warn(hid, "hid_field_extract() called with n (%d) > 32! (%s)\n", n, current->comm); n = 32; } return __extract(report, offset, n); } EXPORT_SYMBOL_GPL(hid_field_extract); /* * "implement" : set bits in a little endian bit stream. * Same concepts as "extract" (see comments above). * The data mangled in the bit stream remains in little endian * order the whole time. It make more sense to talk about * endianness of register values by considering a register * a "cached" copy of the little endian bit stream. */ static void __implement(u8 *report, unsigned offset, int n, u32 value) { unsigned int idx = offset / 8; unsigned int size = offset + n; unsigned int bit_shift = offset % 8; int bits_to_set = 8 - bit_shift; u8 bit_mask = 0xff << bit_shift; while (n - bits_to_set >= 0) { report[idx] &= ~bit_mask; report[idx] |= value << bit_shift; value >>= bits_to_set; n -= bits_to_set; bits_to_set = 8; bit_mask = 0xff; bit_shift = 0; idx++; } /* last nibble */ if (n) { if (size % 8) bit_mask &= (1U << (size % 8)) - 1; report[idx] &= ~bit_mask; report[idx] |= (value << bit_shift) & bit_mask; } } static void implement(const struct hid_device *hid, u8 *report, unsigned offset, unsigned n, u32 value) { u64 m; if (n > 32) { hid_warn(hid, "%s() called with n (%d) > 32! (%s)\n", __func__, n, current->comm); n = 32; } m = (1ULL << n) - 1; if (value > m) hid_warn(hid, "%s() called with too large value %d! (%s)\n", __func__, value, current->comm); WARN_ON(value > m); value &= m; __implement(report, offset, n, value); } /* * Search an array for a value. */ static int search(__s32 *array, __s32 value, unsigned n) { while (n--) { if (*array++ == value) return 0; } return -1; } /** * hid_match_report - check if driver's raw_event should be called * * @hid: hid device * @report_type: type to match against * * compare hid->driver->report_table->report_type to report->type */ static int hid_match_report(struct hid_device *hid, struct hid_report *report) { const struct hid_report_id *id = hid->driver->report_table; if (!id) /* NULL means all */ return 1; for (; id->report_type != HID_TERMINATOR; id++) if (id->report_type == HID_ANY_ID || id->report_type == report->type) return 1; return 0; } /** * hid_match_usage - check if driver's event should be called * * @hid: hid device * @usage: usage to match against * * compare hid->driver->usage_table->usage_{type,code} to * usage->usage_{type,code} */ static int hid_match_usage(struct hid_device *hid, struct hid_usage *usage) { const struct hid_usage_id *id = hid->driver->usage_table; if (!id) /* NULL means all */ return 1; for (; id->usage_type != HID_ANY_ID - 1; id++) if ((id->usage_hid == HID_ANY_ID || id->usage_hid == usage->hid) && (id->usage_type == HID_ANY_ID || id->usage_type == usage->type) && (id->usage_code == HID_ANY_ID || id->usage_code == usage->code)) return 1; return 0; } static void hid_process_event(struct hid_device *hid, struct hid_field *field, struct hid_usage *usage, __s32 value, int interrupt) { struct hid_driver *hdrv = hid->driver; int ret; if (!list_empty(&hid->debug_list)) hid_dump_input(hid, usage, value); if (hdrv && hdrv->event && hid_match_usage(hid, usage)) { ret = hdrv->event(hid, field, usage, value); if (ret != 0) { if (ret < 0) hid_err(hid, "%s's event failed with %d\n", hdrv->name, ret); return; } } if (hid->claimed & HID_CLAIMED_INPUT) hidinput_hid_event(hid, field, usage, value); if (hid->claimed & HID_CLAIMED_HIDDEV && interrupt && hid->hiddev_hid_event) hid->hiddev_hid_event(hid, field, usage, value); } /* * Analyse a received field, and fetch the data from it. The field * content is stored for next report processing (we do differential * reporting to the layer). */ static void hid_input_field(struct hid_device *hid, struct hid_field *field, __u8 *data, int interrupt) { unsigned n; unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; __s32 min = field->logical_minimum; __s32 max = field->logical_maximum; __s32 *value; value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC); if (!value) return; for (n = 0; n < count; n++) { value[n] = min < 0 ? snto32(hid_field_extract(hid, data, offset + n * size, size), size) : hid_field_extract(hid, data, offset + n * size, size); /* Ignore report if ErrorRollOver */ if (!(field->flags & HID_MAIN_ITEM_VARIABLE) && value[n] >= min && value[n] <= max && value[n] - min < field->maxusage && field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) goto exit; } for (n = 0; n < count; n++) { if (HID_MAIN_ITEM_VARIABLE & field->flags) { hid_process_event(hid, field, &field->usage[n], value[n], interrupt); continue; } if (field->value[n] >= min && field->value[n] <= max && field->value[n] - min < field->maxusage && field->usage[field->value[n] - min].hid && search(value, field->value[n], count)) hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt); if (value[n] >= min && value[n] <= max && value[n] - min < field->maxusage && field->usage[value[n] - min].hid && search(field->value, value[n], count)) hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt); } memcpy(field->value, value, count * sizeof(__s32)); exit: kfree(value); } /* * Output the field into the report. */ static void hid_output_field(const struct hid_device *hid, struct hid_field *field, __u8 *data) { unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; unsigned n; for (n = 0; n < count; n++) { if (field->logical_minimum < 0) /* signed values */ implement(hid, data, offset + n * size, size, s32ton(field->value[n], size)); else /* unsigned values */ implement(hid, data, offset + n * size, size, field->value[n]); } } /* * Create a report. 'data' has to be allocated using * hid_alloc_report_buf() so that it has proper size. */ void hid_output_report(struct hid_report *report, __u8 *data) { unsigned n; if (report->id > 0) *data++ = report->id; memset(data, 0, ((report->size - 1) >> 3) + 1); for (n = 0; n < report->maxfield; n++) hid_output_field(report->device, report->field[n], data); } EXPORT_SYMBOL_GPL(hid_output_report); /* * Allocator for buffer that is going to be passed to hid_output_report() */ u8 *hid_alloc_report_buf(struct hid_report *report, gfp_t flags) { /* * 7 extra bytes are necessary to achieve proper functionality * of implement() working on 8 byte chunks */ int len = hid_report_len(report) + 7; return kmalloc(len, flags); } EXPORT_SYMBOL_GPL(hid_alloc_report_buf); /* * Set a field value. The report this field belongs to has to be * created and transferred to the device, to set this value in the * device. */ int hid_set_field(struct hid_field *field, unsigned offset, __s32 value) { unsigned size; if (!field) return -1; size = field->report_size; hid_dump_input(field->report->device, field->usage + offset, value); if (offset >= field->report_count) { hid_err(field->report->device, "offset (%d) exceeds report_count (%d)\n", offset, field->report_count); return -1; } if (field->logical_minimum < 0) { if (value != snto32(s32ton(value, size), size)) { hid_err(field->report->device, "value %d is out of range\n", value); return -1; } } field->value[offset] = value; return 0; } EXPORT_SYMBOL_GPL(hid_set_field); static struct hid_report *hid_get_report(struct hid_report_enum *report_enum, const u8 *data) { struct hid_report *report; unsigned int n = 0; /* Normally report number is 0 */ /* Device uses numbered reports, data[0] is report number */ if (report_enum->numbered) n = *data; report = report_enum->report_id_hash[n]; if (report == NULL) dbg_hid("undefined report_id %u received\n", n); return report; } /* * Implement a generic .request() callback, using .raw_request() * DO NOT USE in hid drivers directly, but through hid_hw_request instead. */ void __hid_request(struct hid_device *hid, struct hid_report *report, int reqtype) { char *buf; int ret; int len; buf = hid_alloc_report_buf(report, GFP_KERNEL); if (!buf) return; len = hid_report_len(report); if (reqtype == HID_REQ_SET_REPORT) hid_output_report(report, buf); ret = hid->ll_driver->raw_request(hid, report->id, buf, len, report->type, reqtype); if (ret < 0) { dbg_hid("unable to complete request: %d\n", ret); goto out; } if (reqtype == HID_REQ_GET_REPORT) hid_input_report(hid, report->type, buf, ret, 0); out: kfree(buf); } EXPORT_SYMBOL_GPL(__hid_request); int hid_report_raw_event(struct hid_device *hid, int type, u8 *data, int size, int interrupt) { struct hid_report_enum *report_enum = hid->report_enum + type; struct hid_report *report; struct hid_driver *hdrv; unsigned int a; int rsize, csize = size; u8 *cdata = data; int ret = 0; report = hid_get_report(report_enum, data); if (!report) goto out; if (report_enum->numbered) { cdata++; csize--; } rsize = ((report->size - 1) >> 3) + 1; if (rsize > HID_MAX_BUFFER_SIZE) rsize = HID_MAX_BUFFER_SIZE; if (csize < rsize) { dbg_hid("report %d is too short, (%d < %d)\n", report->id, csize, rsize); memset(cdata + csize, 0, rsize - csize); } if ((hid->claimed & HID_CLAIMED_HIDDEV) && hid->hiddev_report_event) hid->hiddev_report_event(hid, report); if (hid->claimed & HID_CLAIMED_HIDRAW) { ret = hidraw_report_event(hid, data, size); if (ret) goto out; } if (hid->claimed != HID_CLAIMED_HIDRAW && report->maxfield) { for (a = 0; a < report->maxfield; a++) hid_input_field(hid, report->field[a], cdata, interrupt); hdrv = hid->driver; if (hdrv && hdrv->report) hdrv->report(hid, report); } if (hid->claimed & HID_CLAIMED_INPUT) hidinput_report_event(hid, report); out: return ret; } EXPORT_SYMBOL_GPL(hid_report_raw_event); /** * hid_input_report - report data from lower layer (usb, bt...) * * @hid: hid device * @type: HID report type (HID_*_REPORT) * @data: report contents * @size: size of data parameter * @interrupt: distinguish between interrupt and control transfers * * This is data entry for lower layers. */ int hid_input_report(struct hid_device *hid, int type, u8 *data, int size, int interrupt) { struct hid_report_enum *report_enum; struct hid_driver *hdrv; struct hid_report *report; int ret = 0; if (!hid) return -ENODEV; if (down_trylock(&hid->driver_input_lock)) return -EBUSY; if (!hid->driver) { ret = -ENODEV; goto unlock; } report_enum = hid->report_enum + type; hdrv = hid->driver; if (!size) { dbg_hid("empty report\n"); ret = -1; goto unlock; } /* Avoid unnecessary overhead if debugfs is disabled */ if (!list_empty(&hid->debug_list)) hid_dump_report(hid, type, data, size); report = hid_get_report(report_enum, data); if (!report) { ret = -1; goto unlock; } if (hdrv && hdrv->raw_event && hid_match_report(hid, report)) { ret = hdrv->raw_event(hid, report, data, size); if (ret < 0) goto unlock; } ret = hid_report_raw_event(hid, type, data, size, interrupt); unlock: up(&hid->driver_input_lock); return ret; } EXPORT_SYMBOL_GPL(hid_input_report); static bool hid_match_one_id(struct hid_device *hdev, const struct hid_device_id *id) { return (id->bus == HID_BUS_ANY || id->bus == hdev->bus) && (id->group == HID_GROUP_ANY || id->group == hdev->group) && (id->vendor == HID_ANY_ID || id->vendor == hdev->vendor) && (id->product == HID_ANY_ID || id->product == hdev->product); } const struct hid_device_id *hid_match_id(struct hid_device *hdev, const struct hid_device_id *id) { for (; id->bus; id++) if (hid_match_one_id(hdev, id)) return id; return NULL; } static const struct hid_device_id hid_hiddev_list[] = { { HID_USB_DEVICE(USB_VENDOR_ID_MGE, USB_DEVICE_ID_MGE_UPS) }, { HID_USB_DEVICE(USB_VENDOR_ID_MGE, USB_DEVICE_ID_MGE_UPS1) }, { } }; static bool hid_hiddev(struct hid_device *hdev) { return !!hid_match_id(hdev, hid_hiddev_list); } static ssize_t read_report_descriptor(struct file *filp, struct kobject *kobj, struct bin_attribute *attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj); struct hid_device *hdev = to_hid_device(dev); if (off >= hdev->rsize) return 0; if (off + count > hdev->rsize) count = hdev->rsize - off; memcpy(buf, hdev->rdesc + off, count); return count; } static ssize_t show_country(struct device *dev, struct device_attribute *attr, char *buf) { struct hid_device *hdev = to_hid_device(dev); return sprintf(buf, "%02x\n", hdev->country & 0xff); } static struct bin_attribute dev_bin_attr_report_desc = { .attr = { .name = "report_descriptor", .mode = 0444 }, .read = read_report_descriptor, .size = HID_MAX_DESCRIPTOR_SIZE, }; static struct device_attribute dev_attr_country = { .attr = { .name = "country", .mode = 0444 }, .show = show_country, }; int hid_connect(struct hid_device *hdev, unsigned int connect_mask) { static const char *types[] = { "Device", "Pointer", "Mouse", "Device", "Joystick", "Gamepad", "Keyboard", "Keypad", "Multi-Axis Controller" }; const char *type, *bus; char buf[64] = ""; unsigned int i; int len; int ret; if (hdev->quirks & HID_QUIRK_HIDDEV_FORCE) connect_mask |= (HID_CONNECT_HIDDEV_FORCE | HID_CONNECT_HIDDEV); if (hdev->quirks & HID_QUIRK_HIDINPUT_FORCE) connect_mask |= HID_CONNECT_HIDINPUT_FORCE; if (hdev->bus != BUS_USB) connect_mask &= ~HID_CONNECT_HIDDEV; if (hid_hiddev(hdev)) connect_mask |= HID_CONNECT_HIDDEV_FORCE; if ((connect_mask & HID_CONNECT_HIDINPUT) && !hidinput_connect(hdev, connect_mask & HID_CONNECT_HIDINPUT_FORCE)) hdev->claimed |= HID_CLAIMED_INPUT; if ((connect_mask & HID_CONNECT_HIDDEV) && hdev->hiddev_connect && !hdev->hiddev_connect(hdev, connect_mask & HID_CONNECT_HIDDEV_FORCE)) hdev->claimed |= HID_CLAIMED_HIDDEV; if ((connect_mask & HID_CONNECT_HIDRAW) && !hidraw_connect(hdev)) hdev->claimed |= HID_CLAIMED_HIDRAW; if (connect_mask & HID_CONNECT_DRIVER) hdev->claimed |= HID_CLAIMED_DRIVER; /* Drivers with the ->raw_event callback set are not required to connect * to any other listener. */ if (!hdev->claimed && !hdev->driver->raw_event) { hid_err(hdev, "device has no listeners, quitting\n"); return -ENODEV; } if ((hdev->claimed & HID_CLAIMED_INPUT) && (connect_mask & HID_CONNECT_FF) && hdev->ff_init) hdev->ff_init(hdev); len = 0; if (hdev->claimed & HID_CLAIMED_INPUT) len += sprintf(buf + len, "input"); if (hdev->claimed & HID_CLAIMED_HIDDEV) len += sprintf(buf + len, "%shiddev%d", len ? "," : "", hdev->minor); if (hdev->claimed & HID_CLAIMED_HIDRAW) len += sprintf(buf + len, "%shidraw%d", len ? "," : "", ((struct hidraw *)hdev->hidraw)->minor); type = "Device"; for (i = 0; i < hdev->maxcollection; i++) { struct hid_collection *col = &hdev->collection[i]; if (col->type == HID_COLLECTION_APPLICATION && (col->usage & HID_USAGE_PAGE) == HID_UP_GENDESK && (col->usage & 0xffff) < ARRAY_SIZE(types)) { type = types[col->usage & 0xffff]; break; } } switch (hdev->bus) { case BUS_USB: bus = "USB"; break; case BUS_BLUETOOTH: bus = "BLUETOOTH"; break; case BUS_I2C: bus = "I2C"; break; default: bus = "<UNKNOWN>"; } ret = device_create_file(&hdev->dev, &dev_attr_country); if (ret) hid_warn(hdev, "can't create sysfs country code attribute err: %d\n", ret); hid_info(hdev, "%s: %s HID v%x.%02x %s [%s] on %s\n", buf, bus, hdev->version >> 8, hdev->version & 0xff, type, hdev->name, hdev->phys); return 0; } EXPORT_SYMBOL_GPL(hid_connect); void hid_disconnect(struct hid_device *hdev) { device_remove_file(&hdev->dev, &dev_attr_country); if (hdev->claimed & HID_CLAIMED_INPUT) hidinput_disconnect(hdev); if (hdev->claimed & HID_CLAIMED_HIDDEV) hdev->hiddev_disconnect(hdev); if (hdev->claimed & HID_CLAIMED_HIDRAW) hidraw_disconnect(hdev); hdev->claimed = 0; } EXPORT_SYMBOL_GPL(hid_disconnect); /* * A list of devices for which there is a specialized driver on HID bus. * * Please note that for multitouch devices (driven by hid-multitouch driver), * there is a proper autodetection and autoloading in place (based on presence * of HID_DG_CONTACTID), so those devices don't need to be added to this list, * as we are doing the right thing in hid_scan_usage(). * * Autodetection for (USB) HID sensor hubs exists too. If a collection of type * physical is found inside a usage page of type sensor, hid-sensor-hub will be * used as a driver. See hid_scan_report(). */ static const struct hid_device_id hid_have_special_driver[] = { { HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_WCP32PU) }, { HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_X5_005D) }, { HID_USB_DEVICE(USB_VENDOR_ID_A4TECH, USB_DEVICE_ID_A4TECH_RP_649) }, { HID_USB_DEVICE(USB_VENDOR_ID_ACRUX, 0x0802) }, { HID_USB_DEVICE(USB_VENDOR_ID_ACRUX, 0xf705) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_MIGHTYMOUSE) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_MAGICMOUSE) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_MAGICTRACKPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_MINI_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_MINI_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_MINI_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL2) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL3) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL4) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_IRCONTROL5) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_ANSI) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_ISO) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_REVB_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_JIS) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2009_ANSI) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2009_ISO) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2009_JIS) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2011_ANSI) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2011_ISO) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_ALU_WIRELESS_2011_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_TP_ONLY) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER1_TP_ONLY) }, { HID_USB_DEVICE(USB_VENDOR_ID_AUREAL, USB_DEVICE_ID_AUREAL_W01RN) }, { HID_USB_DEVICE(USB_VENDOR_ID_BELKIN, USB_DEVICE_ID_FLIP_KVM) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185BFM, 0x2208) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185PC, 0x5506) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2PC, 0x1850) }, { HID_USB_DEVICE(USB_VENDOR_ID_BETOP_2185V2BFM, 0x5500) }, { HID_USB_DEVICE(USB_VENDOR_ID_BTC, USB_DEVICE_ID_BTC_EMPREX_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_BTC, USB_DEVICE_ID_BTC_EMPREX_REMOTE_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHERRY, USB_DEVICE_ID_CHERRY_CYMOTION) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHERRY, USB_DEVICE_ID_CHERRY_CYMOTION_SOLAR) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_TACTICAL_PAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_WIRELESS) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_WIRELESS2) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_AK1D) }, { HID_USB_DEVICE(USB_VENDOR_ID_CHICONY, USB_DEVICE_ID_CHICONY_ACER_SWITCH12) }, { HID_USB_DEVICE(USB_VENDOR_ID_CORSAIR, USB_DEVICE_ID_CORSAIR_K90) }, { HID_USB_DEVICE(USB_VENDOR_ID_CREATIVELABS, USB_DEVICE_ID_PRODIKEYS_PCMIDI) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_CP2112) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_1) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_BARCODE_4) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_DRAGONRISE, 0x0006) }, { HID_USB_DEVICE(USB_VENDOR_ID_DRAGONRISE, 0x0011) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_ELECOM, USB_DEVICE_ID_ELECOM_BM084) }, { HID_USB_DEVICE(USB_VENDOR_ID_ELO, 0x0009) }, { HID_USB_DEVICE(USB_VENDOR_ID_ELO, 0x0030) }, { HID_USB_DEVICE(USB_VENDOR_ID_EMS, USB_DEVICE_ID_EMS_TRIO_LINKER_PLUS_II) }, { HID_USB_DEVICE(USB_VENDOR_ID_EZKEY, USB_DEVICE_ID_BTC_8193) }, { HID_USB_DEVICE(USB_VENDOR_ID_GAMERON, USB_DEVICE_ID_GAMERON_DUAL_PSX_ADAPTOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_GAMERON, USB_DEVICE_ID_GAMERON_DUAL_PCS_ADAPTOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_GEMBIRD, USB_DEVICE_ID_GEMBIRD_JPD_DUALFORCE2) }, { HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0003) }, { HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012) }, { HID_USB_DEVICE(USB_VENDOR_ID_GYRATION, USB_DEVICE_ID_GYRATION_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_GYRATION, USB_DEVICE_ID_GYRATION_REMOTE_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_GYRATION, USB_DEVICE_ID_GYRATION_REMOTE_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK, USB_DEVICE_ID_HOLTEK_ON_LINE_GRIP) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A04A) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A067) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A070) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A072) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A081) }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A0C2) }, { HID_USB_DEVICE(USB_VENDOR_ID_HUION, USB_DEVICE_ID_HUION_TABLET) }, { HID_USB_DEVICE(USB_VENDOR_ID_JESS2, USB_DEVICE_ID_JESS2_COLOR_RUMBLE_PAD) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_ION, USB_DEVICE_ID_ICADE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KENSINGTON, USB_DEVICE_ID_KS_SLIMBLADE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KEYTOUCH, USB_DEVICE_ID_KEYTOUCH_IEC) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_MANTICORE) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_GENIUS_GX_IMPERATOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_ERGO_525V) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_I405X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_MOUSEPEN_I608X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_MOUSEPEN_I608X_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_EASYPEN_M610X) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_PENSKETCH_M912) }, { HID_USB_DEVICE(USB_VENDOR_ID_LABTEC, USB_DEVICE_ID_LABTEC_WIRELESS_KEYBOARD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LCPOWER, USB_DEVICE_ID_LCPOWER_LC1000 ) }, #if IS_ENABLED(CONFIG_HID_LENOVO) { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_TPKBD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_CUSBKBD) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_CBTKBD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LENOVO, USB_DEVICE_ID_LENOVO_TPPRODOCK) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_MX3000_RECEIVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_S510_RECEIVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_S510_RECEIVER_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RECEIVER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_HARMONY_PS3) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_T651) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_DESKTOP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_EDGE) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_DINOVO_MINI) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_ELITE_KBD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_CORDLESS_DESKTOP_LX500) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_EXTREME_3D) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD_CORD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD2_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G29_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G920_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WINGMAN_F3D) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WINGMAN_FFG ) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_FORCE3D_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_FLIGHT_SYSTEM_G940) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_MOMO_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DFP_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_DFGT_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G25_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G27_WHEEL) }, #if IS_ENABLED(CONFIG_HID_LOGITECH_DJ) { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_UNIFYING_RECEIVER_2) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_WII_WHEEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_RUMBLEPAD2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_SPACETRAVELLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_SPACENAVIGATOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD_BOOTLOADER) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_COMFORT_MOUSE_4500) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_SIDEWINDER_GV) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_NE4K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_NE4K_JP) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_NE7K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_LK6K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_PRESENTER_8K_USB) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_DIGITAL_MEDIA_3K) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_WIRELESS_OPTICAL_DESKTOP_3_0) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_OFFICE_KB) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_PRO_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_PRO_3_JP) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_TYPE_COVER_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_POWER_COVER) }, { HID_USB_DEVICE(USB_VENDOR_ID_MONTEREY, USB_DEVICE_ID_GENIUS_KB29E) }, { HID_USB_DEVICE(USB_VENDOR_ID_MSI, USB_DEVICE_ID_MSI_GT683R_LED_PANEL) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_1) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_2) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_4) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_5) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_6) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_7) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_8) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_9) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_10) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_11) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_12) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_13) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_14) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_15) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_16) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_17) }, { HID_USB_DEVICE(USB_VENDOR_ID_NTRIG, USB_DEVICE_ID_NTRIG_TOUCH_SCREEN_18) }, { HID_USB_DEVICE(USB_VENDOR_ID_ORTEK, USB_DEVICE_ID_ORTEK_PKB1700) }, { HID_USB_DEVICE(USB_VENDOR_ID_ORTEK, USB_DEVICE_ID_ORTEK_WKB2000) }, { HID_USB_DEVICE(USB_VENDOR_ID_PENMOUNT, USB_DEVICE_ID_PENMOUNT_6000) }, { HID_USB_DEVICE(USB_VENDOR_ID_PETALYNX, USB_DEVICE_ID_PETALYNX_MAXTER_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_PLANTRONICS, HID_ANY_ID) }, { HID_USB_DEVICE(USB_VENDOR_ID_PRIMAX, USB_DEVICE_ID_PRIMAX_KEYBOARD) }, #if IS_ENABLED(CONFIG_HID_ROCCAT) { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_ARVO) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_ISKU) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_ISKUFX) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONE) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEPLUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEPURE) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEPURE_OPTICAL) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KONEXTD) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_KOVAPLUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_LUA) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_PYRA_WIRED) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_PYRA_WIRELESS) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_RYOS_MK) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_RYOS_MK_GLOW) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_RYOS_MK_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_ROCCAT, USB_DEVICE_ID_ROCCAT_SAVU) }, #endif #if IS_ENABLED(CONFIG_HID_SAITEK) { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_PS1000) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_RAT7_OLD) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_RAT7) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAITEK, USB_DEVICE_ID_SAITEK_MMO7) }, { HID_USB_DEVICE(USB_VENDOR_ID_MADCATZ, USB_DEVICE_ID_MADCATZ_RAT5) }, { HID_USB_DEVICE(USB_VENDOR_ID_MADCATZ, USB_DEVICE_ID_MADCATZ_RAT9) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_SAMSUNG, USB_DEVICE_ID_SAMSUNG_IR_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SAMSUNG, USB_DEVICE_ID_SAMSUNG_WIRELESS_KBD_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SKYCABLE, USB_DEVICE_ID_SKYCABLE_WIRELESS_PRESENTER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SMK, USB_DEVICE_ID_SMK_PS3_BDREMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_BUZZ_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_WIRELESS_BUZZ_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_MOTION_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_NAVIGATION_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_BDREMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS3_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_PS4_CONTROLLER) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGX_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_SONY, USB_DEVICE_ID_SONY_VAIO_VGP_MOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_STEELSERIES, USB_DEVICE_ID_STEELSERIES_SRWS1) }, { HID_USB_DEVICE(USB_VENDOR_ID_SUNPLUS, USB_DEVICE_ID_SUNPLUS_WDESKTOP) }, { HID_USB_DEVICE(USB_VENDOR_ID_THINGM, USB_DEVICE_ID_BLINK1) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb300) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb304) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb323) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb324) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb651) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb653) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb654) }, { HID_USB_DEVICE(USB_VENDOR_ID_THRUSTMASTER, 0xb65a) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_TIVO, USB_DEVICE_ID_TIVO_SLIDE_BT) }, { HID_USB_DEVICE(USB_VENDOR_ID_TIVO, USB_DEVICE_ID_TIVO_SLIDE) }, { HID_USB_DEVICE(USB_VENDOR_ID_TIVO, USB_DEVICE_ID_TIVO_SLIDE_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_TOPSEED, USB_DEVICE_ID_TOPSEED_CYBERLINK) }, { HID_USB_DEVICE(USB_VENDOR_ID_TOPSEED2, USB_DEVICE_ID_TOPSEED2_RF_COMBO) }, { HID_USB_DEVICE(USB_VENDOR_ID_TWINHAN, USB_DEVICE_ID_TWINHAN_IR_REMOTE) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_PF1209) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP4030U) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP5540U) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP8060U) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_WP1062) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_WIRELESS_TABLET_TWHL850) }, { HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC, USB_DEVICE_ID_UCLOGIC_TABLET_TWHA60) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_SMARTJOY_PLUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_SUPER_JOY_BOX_3) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP, USB_DEVICE_ID_DUAL_USB_JOYPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP_LTD, USB_DEVICE_ID_SUPER_JOY_BOX_3_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP_LTD, USB_DEVICE_ID_SUPER_DUAL_BOX_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_WISEGROUP_LTD, USB_DEVICE_ID_SUPER_JOY_BOX_5_PRO) }, { HID_USB_DEVICE(USB_VENDOR_ID_PLAYDOTCOM, USB_DEVICE_ID_PLAYDOTCOM_EMS_USBII) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_SLIM_TABLET_5_8_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_SLIM_TABLET_12_1_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_Q_PAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_PID_0038) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_MEDIA_TABLET_10_6_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_MEDIA_TABLET_14_1_INCH) }, { HID_USB_DEVICE(USB_VENDOR_ID_WALTOP, USB_DEVICE_ID_WALTOP_SIRIUS_BATTERY_FREE_TABLET) }, { HID_USB_DEVICE(USB_VENDOR_ID_X_TENSIONS, USB_DEVICE_ID_SPEEDLINK_VAD_CEZANNE) }, { HID_USB_DEVICE(USB_VENDOR_ID_XIN_MO, USB_DEVICE_ID_XIN_MO_DUAL_ARCADE) }, { HID_USB_DEVICE(USB_VENDOR_ID_ZEROPLUS, 0x0005) }, { HID_USB_DEVICE(USB_VENDOR_ID_ZEROPLUS, 0x0030) }, { HID_USB_DEVICE(USB_VENDOR_ID_ZYDACRON, USB_DEVICE_ID_ZYDACRON_REMOTE_CONTROL) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_MICROSOFT, USB_DEVICE_ID_MS_PRESENTER_8K_BT) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, USB_DEVICE_ID_NINTENDO_WIIMOTE) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO, USB_DEVICE_ID_NINTENDO_WIIMOTE2) }, { HID_USB_DEVICE(USB_VENDOR_ID_RAZER, USB_DEVICE_ID_RAZER_BLADE_14) }, { } }; struct hid_dynid { struct list_head list; struct hid_device_id id; }; /** * store_new_id - add a new HID device ID to this driver and re-probe devices * @driver: target device driver * @buf: buffer for scanning device ID data * @count: input size * * Adds a new dynamic hid device ID to this driver, * and causes the driver to probe for all devices again. */ static ssize_t store_new_id(struct device_driver *drv, const char *buf, size_t count) { struct hid_driver *hdrv = to_hid_driver(drv); struct hid_dynid *dynid; __u32 bus, vendor, product; unsigned long driver_data = 0; int ret; ret = sscanf(buf, "%x %x %x %lx", &bus, &vendor, &product, &driver_data); if (ret < 3) return -EINVAL; dynid = kzalloc(sizeof(*dynid), GFP_KERNEL); if (!dynid) return -ENOMEM; dynid->id.bus = bus; dynid->id.group = HID_GROUP_ANY; dynid->id.vendor = vendor; dynid->id.product = product; dynid->id.driver_data = driver_data; spin_lock(&hdrv->dyn_lock); list_add_tail(&dynid->list, &hdrv->dyn_list); spin_unlock(&hdrv->dyn_lock); ret = driver_attach(&hdrv->driver); return ret ? : count; } static DRIVER_ATTR(new_id, S_IWUSR, NULL, store_new_id); static void hid_free_dynids(struct hid_driver *hdrv) { struct hid_dynid *dynid, *n; spin_lock(&hdrv->dyn_lock); list_for_each_entry_safe(dynid, n, &hdrv->dyn_list, list) { list_del(&dynid->list); kfree(dynid); } spin_unlock(&hdrv->dyn_lock); } static const struct hid_device_id *hid_match_device(struct hid_device *hdev, struct hid_driver *hdrv) { struct hid_dynid *dynid; spin_lock(&hdrv->dyn_lock); list_for_each_entry(dynid, &hdrv->dyn_list, list) { if (hid_match_one_id(hdev, &dynid->id)) { spin_unlock(&hdrv->dyn_lock); return &dynid->id; } } spin_unlock(&hdrv->dyn_lock); return hid_match_id(hdev, hdrv->id_table); } static int hid_bus_match(struct device *dev, struct device_driver *drv) { struct hid_driver *hdrv = to_hid_driver(drv); struct hid_device *hdev = to_hid_device(dev); return hid_match_device(hdev, hdrv) != NULL; } static int hid_device_probe(struct device *dev) { struct hid_driver *hdrv = to_hid_driver(dev->driver); struct hid_device *hdev = to_hid_device(dev); const struct hid_device_id *id; int ret = 0; if (down_interruptible(&hdev->driver_lock)) return -EINTR; if (down_interruptible(&hdev->driver_input_lock)) { ret = -EINTR; goto unlock_driver_lock; } hdev->io_started = false; if (!hdev->driver) { id = hid_match_device(hdev, hdrv); if (id == NULL) { ret = -ENODEV; goto unlock; } hdev->driver = hdrv; if (hdrv->probe) { ret = hdrv->probe(hdev, id); } else { /* default probe */ ret = hid_open_report(hdev); if (!ret) ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT); } if (ret) { hid_close_report(hdev); hdev->driver = NULL; } } unlock: if (!hdev->io_started) up(&hdev->driver_input_lock); unlock_driver_lock: up(&hdev->driver_lock); return ret; } static int hid_device_remove(struct device *dev) { struct hid_device *hdev = to_hid_device(dev); struct hid_driver *hdrv; int ret = 0; if (down_interruptible(&hdev->driver_lock)) return -EINTR; if (down_interruptible(&hdev->driver_input_lock)) { ret = -EINTR; goto unlock_driver_lock; } hdev->io_started = false; hdrv = hdev->driver; if (hdrv) { if (hdrv->remove) hdrv->remove(hdev); else /* default remove */ hid_hw_stop(hdev); hid_close_report(hdev); hdev->driver = NULL; } if (!hdev->io_started) up(&hdev->driver_input_lock); unlock_driver_lock: up(&hdev->driver_lock); return ret; } static ssize_t modalias_show(struct device *dev, struct device_attribute *a, char *buf) { struct hid_device *hdev = container_of(dev, struct hid_device, dev); return scnprintf(buf, PAGE_SIZE, "hid:b%04Xg%04Xv%08Xp%08X\n", hdev->bus, hdev->group, hdev->vendor, hdev->product); } static DEVICE_ATTR_RO(modalias); static struct attribute *hid_dev_attrs[] = { &dev_attr_modalias.attr, NULL, }; static struct bin_attribute *hid_dev_bin_attrs[] = { &dev_bin_attr_report_desc, NULL }; static const struct attribute_group hid_dev_group = { .attrs = hid_dev_attrs, .bin_attrs = hid_dev_bin_attrs, }; __ATTRIBUTE_GROUPS(hid_dev); static int hid_uevent(struct device *dev, struct kobj_uevent_env *env) { struct hid_device *hdev = to_hid_device(dev); if (add_uevent_var(env, "HID_ID=%04X:%08X:%08X", hdev->bus, hdev->vendor, hdev->product)) return -ENOMEM; if (add_uevent_var(env, "HID_NAME=%s", hdev->name)) return -ENOMEM; if (add_uevent_var(env, "HID_PHYS=%s", hdev->phys)) return -ENOMEM; if (add_uevent_var(env, "HID_UNIQ=%s", hdev->uniq)) return -ENOMEM; if (add_uevent_var(env, "MODALIAS=hid:b%04Xg%04Xv%08Xp%08X", hdev->bus, hdev->group, hdev->vendor, hdev->product)) return -ENOMEM; return 0; } static struct bus_type hid_bus_type = { .name = "hid", .dev_groups = hid_dev_groups, .match = hid_bus_match, .probe = hid_device_probe, .remove = hid_device_remove, .uevent = hid_uevent, }; /* a list of devices that shouldn't be handled by HID core at all */ static const struct hid_device_id hid_ignore_list[] = { { HID_USB_DEVICE(USB_VENDOR_ID_ACECAD, USB_DEVICE_ID_ACECAD_FLAIR) }, { HID_USB_DEVICE(USB_VENDOR_ID_ACECAD, USB_DEVICE_ID_ACECAD_302) }, { HID_USB_DEVICE(USB_VENDOR_ID_ADS_TECH, USB_DEVICE_ID_ADS_TECH_RADIO_SI470X) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_01) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_10) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_20) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_21) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_22) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_23) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIPTEK, USB_DEVICE_ID_AIPTEK_24) }, { HID_USB_DEVICE(USB_VENDOR_ID_AIRCABLE, USB_DEVICE_ID_AIRCABLE1) }, { HID_USB_DEVICE(USB_VENDOR_ID_ALCOR, USB_DEVICE_ID_ALCOR_USBRS232) }, { HID_USB_DEVICE(USB_VENDOR_ID_ASUSTEK, USB_DEVICE_ID_ASUSTEK_LCM)}, { HID_USB_DEVICE(USB_VENDOR_ID_ASUSTEK, USB_DEVICE_ID_ASUSTEK_LCM2)}, { HID_USB_DEVICE(USB_VENDOR_ID_AVERMEDIA, USB_DEVICE_ID_AVER_FM_MR800) }, { HID_USB_DEVICE(USB_VENDOR_ID_AXENTIA, USB_DEVICE_ID_AXENTIA_FM_RADIO) }, { HID_USB_DEVICE(USB_VENDOR_ID_BERKSHIRE, USB_DEVICE_ID_BERKSHIRE_PCWD) }, { HID_USB_DEVICE(USB_VENDOR_ID_CIDC, 0x0103) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_RADIO_SI470X) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_RADIO_SI4713) }, { HID_USB_DEVICE(USB_VENDOR_ID_CMEDIA, USB_DEVICE_ID_CM109) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_HIDCOM) }, { HID_USB_DEVICE(USB_VENDOR_ID_CYPRESS, USB_DEVICE_ID_CYPRESS_ULTRAMOUSE) }, { HID_USB_DEVICE(USB_VENDOR_ID_DEALEXTREAME, USB_DEVICE_ID_DEALEXTREAME_RADIO_SI4701) }, { HID_USB_DEVICE(USB_VENDOR_ID_DELORME, USB_DEVICE_ID_DELORME_EARTHMATE) }, { HID_USB_DEVICE(USB_VENDOR_ID_DELORME, USB_DEVICE_ID_DELORME_EM_LT20) }, { HID_USB_DEVICE(USB_VENDOR_ID_DREAM_CHEEKY, 0x0004) }, { HID_USB_DEVICE(USB_VENDOR_ID_DREAM_CHEEKY, 0x000a) }, { HID_I2C_DEVICE(USB_VENDOR_ID_ELAN, 0x0400) }, { HID_I2C_DEVICE(USB_VENDOR_ID_ELAN, 0x0401) }, { HID_USB_DEVICE(USB_VENDOR_ID_ESSENTIAL_REALITY, USB_DEVICE_ID_ESSENTIAL_REALITY_P5) }, { HID_USB_DEVICE(USB_VENDOR_ID_ETT, USB_DEVICE_ID_TC5UH) }, { HID_USB_DEVICE(USB_VENDOR_ID_ETT, USB_DEVICE_ID_TC4UM) }, { HID_USB_DEVICE(USB_VENDOR_ID_GENERAL_TOUCH, 0x0001) }, { HID_USB_DEVICE(USB_VENDOR_ID_GENERAL_TOUCH, 0x0002) }, { HID_USB_DEVICE(USB_VENDOR_ID_GENERAL_TOUCH, 0x0004) }, { HID_USB_DEVICE(USB_VENDOR_ID_GOTOP, USB_DEVICE_ID_SUPER_Q2) }, { HID_USB_DEVICE(USB_VENDOR_ID_GOTOP, USB_DEVICE_ID_GOGOPEN) }, { HID_USB_DEVICE(USB_VENDOR_ID_GOTOP, USB_DEVICE_ID_PENPOWER) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRETAGMACBETH, USB_DEVICE_ID_GRETAGMACBETH_HUEY) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRIFFIN, USB_DEVICE_ID_POWERMATE) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRIFFIN, USB_DEVICE_ID_SOUNDKNOB) }, { HID_USB_DEVICE(USB_VENDOR_ID_GRIFFIN, USB_DEVICE_ID_RADIOSHARK) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_90) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_100) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_101) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_103) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_104) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_105) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_106) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_107) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_108) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_200) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_201) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_202) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_203) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_204) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_205) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_206) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_207) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_300) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_301) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_302) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_303) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_304) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_305) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_306) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_307) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_308) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_309) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_400) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_401) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_402) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_403) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_404) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_405) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_500) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_501) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_502) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_503) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_504) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1000) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1001) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1002) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1003) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1004) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1005) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1006) }, { HID_USB_DEVICE(USB_VENDOR_ID_GTCO, USB_DEVICE_ID_GTCO_1007) }, { HID_USB_DEVICE(USB_VENDOR_ID_IMATION, USB_DEVICE_ID_DISC_STAKKA) }, { HID_USB_DEVICE(USB_VENDOR_ID_JABRA, USB_DEVICE_ID_JABRA_SPEAK_410) }, { HID_USB_DEVICE(USB_VENDOR_ID_JABRA, USB_DEVICE_ID_JABRA_SPEAK_510) }, { HID_USB_DEVICE(USB_VENDOR_ID_JABRA, USB_DEVICE_ID_JABRA_GN9350E) }, { HID_USB_DEVICE(USB_VENDOR_ID_KBGEAR, USB_DEVICE_ID_KBGEAR_JAMSTUDIO) }, { HID_USB_DEVICE(USB_VENDOR_ID_KWORLD, USB_DEVICE_ID_KWORLD_RADIO_FM700) }, { HID_USB_DEVICE(USB_VENDOR_ID_KYE, USB_DEVICE_ID_KYE_GPEN_560) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_KYE, 0x0058) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_CASSY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_CASSY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POCKETCASSY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POCKETCASSY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOBILECASSY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOBILECASSY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYVOLTAGE) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYCURRENT) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYTIME) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYTEMPERATURE) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MICROCASSYPH) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_JWM) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_DMMP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIC) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_UMIB) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_XRAY) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_XRAY2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_VIDEOCOM) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOTOR) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_COM3LAB) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_TELEPORT) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_NETWORKANALYSER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_POWERCONTROL) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MACHINETEST) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOSTANALYSER) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MOSTANALYSER2) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_ABSESP) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_AUTODATABUS) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_MCT) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_HYBRID) }, { HID_USB_DEVICE(USB_VENDOR_ID_LD, USB_DEVICE_ID_LD_HEATCONTROL) }, { HID_USB_DEVICE(USB_VENDOR_ID_MADCATZ, USB_DEVICE_ID_MADCATZ_BEATPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_MCC, USB_DEVICE_ID_MCC_PMD1024LS) }, { HID_USB_DEVICE(USB_VENDOR_ID_MCC, USB_DEVICE_ID_MCC_PMD1208LS) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICKIT1) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICKIT2) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICK16F1454) }, { HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICK16F1454_V2) }, { HID_USB_DEVICE(USB_VENDOR_ID_NATIONAL_SEMICONDUCTOR, USB_DEVICE_ID_N_S_HARMONY) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 20) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 30) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 100) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 108) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 118) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 200) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 300) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 400) }, { HID_USB_DEVICE(USB_VENDOR_ID_ONTRAK, USB_DEVICE_ID_ONTRAK_ADU100 + 500) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0001) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0002) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0003) }, { HID_USB_DEVICE(USB_VENDOR_ID_PANJIT, 0x0004) }, { HID_USB_DEVICE(USB_VENDOR_ID_PHILIPS, USB_DEVICE_ID_PHILIPS_IEEE802154_DONGLE) }, { HID_USB_DEVICE(USB_VENDOR_ID_POWERCOM, USB_DEVICE_ID_POWERCOM_UPS) }, #if defined(CONFIG_MOUSE_SYNAPTICS_USB) || defined(CONFIG_MOUSE_SYNAPTICS_USB_MODULE) { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_TP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_INT_TP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_CPAD) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_STICK) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_WP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_COMP_TP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_WTP) }, { HID_USB_DEVICE(USB_VENDOR_ID_SYNAPTICS, USB_DEVICE_ID_SYNAPTICS_DPAD) }, #endif { HID_USB_DEVICE(USB_VENDOR_ID_YEALINK, USB_DEVICE_ID_YEALINK_P1K_P4K_B2K) }, { HID_USB_DEVICE(USB_VENDOR_ID_RISO_KAGAKU, USB_DEVICE_ID_RI_KA_WEBMAIL) }, { } }; /** * hid_mouse_ignore_list - mouse devices which should not be handled by the hid layer * * There are composite devices for which we want to ignore only a certain * interface. This is a list of devices for which only the mouse interface will * be ignored. This allows a dedicated driver to take care of the interface. */ static const struct hid_device_id hid_mouse_ignore_list[] = { /* appletouch driver */ { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER4_HF_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING2_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING3_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING5A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING6A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING7A_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING8_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ANSI) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_ISO) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_WELLSPRING9_JIS) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_FOUNTAIN_TP_ONLY) }, { HID_USB_DEVICE(USB_VENDOR_ID_APPLE, USB_DEVICE_ID_APPLE_GEYSER1_TP_ONLY) }, { } }; bool hid_ignore(struct hid_device *hdev) { if (hdev->quirks & HID_QUIRK_NO_IGNORE) return false; if (hdev->quirks & HID_QUIRK_IGNORE) return true; switch (hdev->vendor) { case USB_VENDOR_ID_CODEMERCS: /* ignore all Code Mercenaries IOWarrior devices */ if (hdev->product >= USB_DEVICE_ID_CODEMERCS_IOW_FIRST && hdev->product <= USB_DEVICE_ID_CODEMERCS_IOW_LAST) return true; break; case USB_VENDOR_ID_LOGITECH: if (hdev->product >= USB_DEVICE_ID_LOGITECH_HARMONY_FIRST && hdev->product <= USB_DEVICE_ID_LOGITECH_HARMONY_LAST) return true; /* * The Keene FM transmitter USB device has the same USB ID as * the Logitech AudioHub Speaker, but it should ignore the hid. * Check if the name is that of the Keene device. * For reference: the name of the AudioHub is * "HOLTEK AudioHub Speaker". */ if (hdev->product == USB_DEVICE_ID_LOGITECH_AUDIOHUB && !strcmp(hdev->name, "HOLTEK B-LINK USB Audio ")) return true; break; case USB_VENDOR_ID_SOUNDGRAPH: if (hdev->product >= USB_DEVICE_ID_SOUNDGRAPH_IMON_FIRST && hdev->product <= USB_DEVICE_ID_SOUNDGRAPH_IMON_LAST) return true; break; case USB_VENDOR_ID_HANWANG: if (hdev->product >= USB_DEVICE_ID_HANWANG_TABLET_FIRST && hdev->product <= USB_DEVICE_ID_HANWANG_TABLET_LAST) return true; break; case USB_VENDOR_ID_JESS: if (hdev->product == USB_DEVICE_ID_JESS_YUREX && hdev->type == HID_TYPE_USBNONE) return true; break; case USB_VENDOR_ID_VELLEMAN: /* These are not HID devices. They are handled by comedi. */ if ((hdev->product >= USB_DEVICE_ID_VELLEMAN_K8055_FIRST && hdev->product <= USB_DEVICE_ID_VELLEMAN_K8055_LAST) || (hdev->product >= USB_DEVICE_ID_VELLEMAN_K8061_FIRST && hdev->product <= USB_DEVICE_ID_VELLEMAN_K8061_LAST)) return true; break; case USB_VENDOR_ID_ATMEL_V_USB: /* Masterkit MA901 usb radio based on Atmel tiny85 chip and * it has the same USB ID as many Atmel V-USB devices. This * usb radio is handled by radio-ma901.c driver so we want * ignore the hid. Check the name, bus, product and ignore * if we have MA901 usb radio. */ if (hdev->product == USB_DEVICE_ID_ATMEL_V_USB && hdev->bus == BUS_USB && strncmp(hdev->name, "www.masterkit.ru MA901", 22) == 0) return true; break; } if (hdev->type == HID_TYPE_USBMOUSE && hid_match_id(hdev, hid_mouse_ignore_list)) return true; return !!hid_match_id(hdev, hid_ignore_list); } EXPORT_SYMBOL_GPL(hid_ignore); int hid_add_device(struct hid_device *hdev) { static atomic_t id = ATOMIC_INIT(0); int ret; if (WARN_ON(hdev->status & HID_STAT_ADDED)) return -EBUSY; /* we need to kill them here, otherwise they will stay allocated to * wait for coming driver */ if (hid_ignore(hdev)) return -ENODEV; /* * Check for the mandatory transport channel. */ if (!hdev->ll_driver->raw_request) { hid_err(hdev, "transport driver missing .raw_request()\n"); return -EINVAL; } /* * Read the device report descriptor once and use as template * for the driver-specific modifications. */ ret = hdev->ll_driver->parse(hdev); if (ret) return ret; if (!hdev->dev_rdesc) return -ENODEV; /* * Scan generic devices for group information */ if (hid_ignore_special_drivers || (!hdev->group && !hid_match_id(hdev, hid_have_special_driver))) { ret = hid_scan_report(hdev); if (ret) hid_warn(hdev, "bad device descriptor (%d)\n", ret); } /* XXX hack, any other cleaner solution after the driver core * is converted to allow more than 20 bytes as the device name? */ dev_set_name(&hdev->dev, "%04X:%04X:%04X.%04X", hdev->bus, hdev->vendor, hdev->product, atomic_inc_return(&id)); hid_debug_register(hdev, dev_name(&hdev->dev)); ret = device_add(&hdev->dev); if (!ret) hdev->status |= HID_STAT_ADDED; else hid_debug_unregister(hdev); return ret; } EXPORT_SYMBOL_GPL(hid_add_device); /** * hid_allocate_device - allocate new hid device descriptor * * Allocate and initialize hid device, so that hid_destroy_device might be * used to free it. * * New hid_device pointer is returned on success, otherwise ERR_PTR encoded * error value. */ struct hid_device *hid_allocate_device(void) { struct hid_device *hdev; int ret = -ENOMEM; hdev = kzalloc(sizeof(*hdev), GFP_KERNEL); if (hdev == NULL) return ERR_PTR(ret); device_initialize(&hdev->dev); hdev->dev.release = hid_device_release; hdev->dev.bus = &hid_bus_type; device_enable_async_suspend(&hdev->dev); hid_close_report(hdev); init_waitqueue_head(&hdev->debug_wait); INIT_LIST_HEAD(&hdev->debug_list); spin_lock_init(&hdev->debug_list_lock); sema_init(&hdev->driver_lock, 1); sema_init(&hdev->driver_input_lock, 1); return hdev; } EXPORT_SYMBOL_GPL(hid_allocate_device); static void hid_remove_device(struct hid_device *hdev) { if (hdev->status & HID_STAT_ADDED) { device_del(&hdev->dev); hid_debug_unregister(hdev); hdev->status &= ~HID_STAT_ADDED; } kfree(hdev->dev_rdesc); hdev->dev_rdesc = NULL; hdev->dev_rsize = 0; } /** * hid_destroy_device - free previously allocated device * * @hdev: hid device * * If you allocate hid_device through hid_allocate_device, you should ever * free by this function. */ void hid_destroy_device(struct hid_device *hdev) { hid_remove_device(hdev); put_device(&hdev->dev); } EXPORT_SYMBOL_GPL(hid_destroy_device); int __hid_register_driver(struct hid_driver *hdrv, struct module *owner, const char *mod_name) { int ret; hdrv->driver.name = hdrv->name; hdrv->driver.bus = &hid_bus_type; hdrv->driver.owner = owner; hdrv->driver.mod_name = mod_name; INIT_LIST_HEAD(&hdrv->dyn_list); spin_lock_init(&hdrv->dyn_lock); ret = driver_register(&hdrv->driver); if (ret) return ret; ret = driver_create_file(&hdrv->driver, &driver_attr_new_id); if (ret) driver_unregister(&hdrv->driver); return ret; } EXPORT_SYMBOL_GPL(__hid_register_driver); void hid_unregister_driver(struct hid_driver *hdrv) { driver_remove_file(&hdrv->driver, &driver_attr_new_id); driver_unregister(&hdrv->driver); hid_free_dynids(hdrv); } EXPORT_SYMBOL_GPL(hid_unregister_driver); int hid_check_keys_pressed(struct hid_device *hid) { struct hid_input *hidinput; int i; if (!(hid->claimed & HID_CLAIMED_INPUT)) return 0; list_for_each_entry(hidinput, &hid->inputs, list) { for (i = 0; i < BITS_TO_LONGS(KEY_MAX); i++) if (hidinput->input->key[i]) return 1; } return 0; } EXPORT_SYMBOL_GPL(hid_check_keys_pressed); static int __init hid_init(void) { int ret; if (hid_debug) pr_warn("hid_debug is now used solely for parser and driver debugging.\n" "debugfs is now used for inspecting the device (report descriptor, reports)\n"); ret = bus_register(&hid_bus_type); if (ret) { pr_err("can't register hid bus\n"); goto err; } ret = hidraw_init(); if (ret) goto err_bus; hid_debug_init(); return 0; err_bus: bus_unregister(&hid_bus_type); err: return ret; } static void __exit hid_exit(void) { hid_debug_exit(); hidraw_exit(); bus_unregister(&hid_bus_type); } module_init(hid_init); module_exit(hid_exit); MODULE_AUTHOR("Andreas Gal"); MODULE_AUTHOR("Vojtech Pavlik"); MODULE_AUTHOR("Jiri Kosina"); MODULE_LICENSE(DRIVER_LICENSE);
./CrossVul/dataset_final_sorted/CWE-125/c/good_5338_0
crossvul-cpp_data_bad_2683_0
/* * Copyright (c) 2001 * Fortress Technologies, Inc. All rights reserved. * Charlie Lenahan (clenahan@fortresstech.com) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IEEE 802.11 printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "cpack.h" /* Lengths of 802.11 header components. */ #define IEEE802_11_FC_LEN 2 #define IEEE802_11_DUR_LEN 2 #define IEEE802_11_DA_LEN 6 #define IEEE802_11_SA_LEN 6 #define IEEE802_11_BSSID_LEN 6 #define IEEE802_11_RA_LEN 6 #define IEEE802_11_TA_LEN 6 #define IEEE802_11_ADDR1_LEN 6 #define IEEE802_11_SEQ_LEN 2 #define IEEE802_11_CTL_LEN 2 #define IEEE802_11_CARRIED_FC_LEN 2 #define IEEE802_11_HT_CONTROL_LEN 4 #define IEEE802_11_IV_LEN 3 #define IEEE802_11_KID_LEN 1 /* Frame check sequence length. */ #define IEEE802_11_FCS_LEN 4 /* Lengths of beacon components. */ #define IEEE802_11_TSTAMP_LEN 8 #define IEEE802_11_BCNINT_LEN 2 #define IEEE802_11_CAPINFO_LEN 2 #define IEEE802_11_LISTENINT_LEN 2 #define IEEE802_11_AID_LEN 2 #define IEEE802_11_STATUS_LEN 2 #define IEEE802_11_REASON_LEN 2 /* Length of previous AP in reassocation frame */ #define IEEE802_11_AP_LEN 6 #define T_MGMT 0x0 /* management */ #define T_CTRL 0x1 /* control */ #define T_DATA 0x2 /* data */ #define T_RESV 0x3 /* reserved */ #define ST_ASSOC_REQUEST 0x0 #define ST_ASSOC_RESPONSE 0x1 #define ST_REASSOC_REQUEST 0x2 #define ST_REASSOC_RESPONSE 0x3 #define ST_PROBE_REQUEST 0x4 #define ST_PROBE_RESPONSE 0x5 /* RESERVED 0x6 */ /* RESERVED 0x7 */ #define ST_BEACON 0x8 #define ST_ATIM 0x9 #define ST_DISASSOC 0xA #define ST_AUTH 0xB #define ST_DEAUTH 0xC #define ST_ACTION 0xD /* RESERVED 0xE */ /* RESERVED 0xF */ static const struct tok st_str[] = { { ST_ASSOC_REQUEST, "Assoc Request" }, { ST_ASSOC_RESPONSE, "Assoc Response" }, { ST_REASSOC_REQUEST, "ReAssoc Request" }, { ST_REASSOC_RESPONSE, "ReAssoc Response" }, { ST_PROBE_REQUEST, "Probe Request" }, { ST_PROBE_RESPONSE, "Probe Response" }, { ST_BEACON, "Beacon" }, { ST_ATIM, "ATIM" }, { ST_DISASSOC, "Disassociation" }, { ST_AUTH, "Authentication" }, { ST_DEAUTH, "DeAuthentication" }, { ST_ACTION, "Action" }, { 0, NULL } }; #define CTRL_CONTROL_WRAPPER 0x7 #define CTRL_BAR 0x8 #define CTRL_BA 0x9 #define CTRL_PS_POLL 0xA #define CTRL_RTS 0xB #define CTRL_CTS 0xC #define CTRL_ACK 0xD #define CTRL_CF_END 0xE #define CTRL_END_ACK 0xF static const struct tok ctrl_str[] = { { CTRL_CONTROL_WRAPPER, "Control Wrapper" }, { CTRL_BAR, "BAR" }, { CTRL_BA, "BA" }, { CTRL_PS_POLL, "Power Save-Poll" }, { CTRL_RTS, "Request-To-Send" }, { CTRL_CTS, "Clear-To-Send" }, { CTRL_ACK, "Acknowledgment" }, { CTRL_CF_END, "CF-End" }, { CTRL_END_ACK, "CF-End+CF-Ack" }, { 0, NULL } }; #define DATA_DATA 0x0 #define DATA_DATA_CF_ACK 0x1 #define DATA_DATA_CF_POLL 0x2 #define DATA_DATA_CF_ACK_POLL 0x3 #define DATA_NODATA 0x4 #define DATA_NODATA_CF_ACK 0x5 #define DATA_NODATA_CF_POLL 0x6 #define DATA_NODATA_CF_ACK_POLL 0x7 #define DATA_QOS_DATA 0x8 #define DATA_QOS_DATA_CF_ACK 0x9 #define DATA_QOS_DATA_CF_POLL 0xA #define DATA_QOS_DATA_CF_ACK_POLL 0xB #define DATA_QOS_NODATA 0xC #define DATA_QOS_CF_POLL_NODATA 0xE #define DATA_QOS_CF_ACK_POLL_NODATA 0xF /* * The subtype field of a data frame is, in effect, composed of 4 flag * bits - CF-Ack, CF-Poll, Null (means the frame doesn't actually have * any data), and QoS. */ #define DATA_FRAME_IS_CF_ACK(x) ((x) & 0x01) #define DATA_FRAME_IS_CF_POLL(x) ((x) & 0x02) #define DATA_FRAME_IS_NULL(x) ((x) & 0x04) #define DATA_FRAME_IS_QOS(x) ((x) & 0x08) /* * Bits in the frame control field. */ #define FC_VERSION(fc) ((fc) & 0x3) #define FC_TYPE(fc) (((fc) >> 2) & 0x3) #define FC_SUBTYPE(fc) (((fc) >> 4) & 0xF) #define FC_TO_DS(fc) ((fc) & 0x0100) #define FC_FROM_DS(fc) ((fc) & 0x0200) #define FC_MORE_FLAG(fc) ((fc) & 0x0400) #define FC_RETRY(fc) ((fc) & 0x0800) #define FC_POWER_MGMT(fc) ((fc) & 0x1000) #define FC_MORE_DATA(fc) ((fc) & 0x2000) #define FC_PROTECTED(fc) ((fc) & 0x4000) #define FC_ORDER(fc) ((fc) & 0x8000) struct mgmt_header_t { uint16_t fc; uint16_t duration; uint8_t da[IEEE802_11_DA_LEN]; uint8_t sa[IEEE802_11_SA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; uint16_t seq_ctrl; }; #define MGMT_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_DA_LEN+IEEE802_11_SA_LEN+\ IEEE802_11_BSSID_LEN+IEEE802_11_SEQ_LEN) #define CAPABILITY_ESS(cap) ((cap) & 0x0001) #define CAPABILITY_IBSS(cap) ((cap) & 0x0002) #define CAPABILITY_CFP(cap) ((cap) & 0x0004) #define CAPABILITY_CFP_REQ(cap) ((cap) & 0x0008) #define CAPABILITY_PRIVACY(cap) ((cap) & 0x0010) struct ssid_t { uint8_t element_id; uint8_t length; u_char ssid[33]; /* 32 + 1 for null */ }; struct rates_t { uint8_t element_id; uint8_t length; uint8_t rate[16]; }; struct challenge_t { uint8_t element_id; uint8_t length; uint8_t text[254]; /* 1-253 + 1 for null */ }; struct fh_t { uint8_t element_id; uint8_t length; uint16_t dwell_time; uint8_t hop_set; uint8_t hop_pattern; uint8_t hop_index; }; struct ds_t { uint8_t element_id; uint8_t length; uint8_t channel; }; struct cf_t { uint8_t element_id; uint8_t length; uint8_t count; uint8_t period; uint16_t max_duration; uint16_t dur_remaing; }; struct tim_t { uint8_t element_id; uint8_t length; uint8_t count; uint8_t period; uint8_t bitmap_control; uint8_t bitmap[251]; }; #define E_SSID 0 #define E_RATES 1 #define E_FH 2 #define E_DS 3 #define E_CF 4 #define E_TIM 5 #define E_IBSS 6 /* reserved 7 */ /* reserved 8 */ /* reserved 9 */ /* reserved 10 */ /* reserved 11 */ /* reserved 12 */ /* reserved 13 */ /* reserved 14 */ /* reserved 15 */ /* reserved 16 */ #define E_CHALLENGE 16 /* reserved 17 */ /* reserved 18 */ /* reserved 19 */ /* reserved 16 */ /* reserved 16 */ struct mgmt_body_t { uint8_t timestamp[IEEE802_11_TSTAMP_LEN]; uint16_t beacon_interval; uint16_t listen_interval; uint16_t status_code; uint16_t aid; u_char ap[IEEE802_11_AP_LEN]; uint16_t reason_code; uint16_t auth_alg; uint16_t auth_trans_seq_num; int challenge_present; struct challenge_t challenge; uint16_t capability_info; int ssid_present; struct ssid_t ssid; int rates_present; struct rates_t rates; int ds_present; struct ds_t ds; int cf_present; struct cf_t cf; int fh_present; struct fh_t fh; int tim_present; struct tim_t tim; }; struct ctrl_control_wrapper_hdr_t { uint16_t fc; uint16_t duration; uint8_t addr1[IEEE802_11_ADDR1_LEN]; uint16_t carried_fc[IEEE802_11_CARRIED_FC_LEN]; uint16_t ht_control[IEEE802_11_HT_CONTROL_LEN]; }; #define CTRL_CONTROL_WRAPPER_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_ADDR1_LEN+\ IEEE802_11_CARRIED_FC_LEN+\ IEEE802_11_HT_CONTROL_LEN) struct ctrl_rts_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; }; #define CTRL_RTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_TA_LEN) struct ctrl_cts_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_CTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_ack_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_ps_poll_hdr_t { uint16_t fc; uint16_t aid; uint8_t bssid[IEEE802_11_BSSID_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; }; #define CTRL_PS_POLL_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_AID_LEN+\ IEEE802_11_BSSID_LEN+IEEE802_11_TA_LEN) struct ctrl_end_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; }; #define CTRL_END_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN) struct ctrl_end_ack_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; }; #define CTRL_END_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN) struct ctrl_ba_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_BA_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_bar_hdr_t { uint16_t fc; uint16_t dur; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; uint16_t ctl; uint16_t seq; }; #define CTRL_BAR_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_TA_LEN+\ IEEE802_11_CTL_LEN+IEEE802_11_SEQ_LEN) struct meshcntl_t { uint8_t flags; uint8_t ttl; uint8_t seq[4]; uint8_t addr4[6]; uint8_t addr5[6]; uint8_t addr6[6]; }; #define IV_IV(iv) ((iv) & 0xFFFFFF) #define IV_PAD(iv) (((iv) >> 24) & 0x3F) #define IV_KEYID(iv) (((iv) >> 30) & 0x03) #define PRINT_SSID(p) \ if (p.ssid_present) { \ ND_PRINT((ndo, " (")); \ fn_print(ndo, p.ssid.ssid, NULL); \ ND_PRINT((ndo, ")")); \ } #define PRINT_RATE(_sep, _r, _suf) \ ND_PRINT((ndo, "%s%2.1f%s", _sep, (.5 * ((_r) & 0x7f)), _suf)) #define PRINT_RATES(p) \ if (p.rates_present) { \ int z; \ const char *sep = " ["; \ for (z = 0; z < p.rates.length ; z++) { \ PRINT_RATE(sep, p.rates.rate[z], \ (p.rates.rate[z] & 0x80 ? "*" : "")); \ sep = " "; \ } \ if (p.rates.length != 0) \ ND_PRINT((ndo, " Mbit]")); \ } #define PRINT_DS_CHANNEL(p) \ if (p.ds_present) \ ND_PRINT((ndo, " CH: %u", p.ds.channel)); \ ND_PRINT((ndo, "%s", \ CAPABILITY_PRIVACY(p.capability_info) ? ", PRIVACY" : "")); #define MAX_MCS_INDEX 76 /* * Indices are: * * the MCS index (0-76); * * 0 for 20 MHz, 1 for 40 MHz; * * 0 for a long guard interval, 1 for a short guard interval. */ static const float ieee80211_float_htrates[MAX_MCS_INDEX+1][2][2] = { /* MCS 0 */ { /* 20 Mhz */ { 6.5, /* SGI */ 7.2, }, /* 40 Mhz */ { 13.5, /* SGI */ 15.0, }, }, /* MCS 1 */ { /* 20 Mhz */ { 13.0, /* SGI */ 14.4, }, /* 40 Mhz */ { 27.0, /* SGI */ 30.0, }, }, /* MCS 2 */ { /* 20 Mhz */ { 19.5, /* SGI */ 21.7, }, /* 40 Mhz */ { 40.5, /* SGI */ 45.0, }, }, /* MCS 3 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 4 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 5 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 6 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 7 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 8 */ { /* 20 Mhz */ { 13.0, /* SGI */ 14.4, }, /* 40 Mhz */ { 27.0, /* SGI */ 30.0, }, }, /* MCS 9 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 10 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 11 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 12 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 13 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 14 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 15 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 16 */ { /* 20 Mhz */ { 19.5, /* SGI */ 21.7, }, /* 40 Mhz */ { 40.5, /* SGI */ 45.0, }, }, /* MCS 17 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 18 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 19 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 20 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 21 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 22 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 23 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 24 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 25 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 26 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 27 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 28 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 29 */ { /* 20 Mhz */ { 208.0, /* SGI */ 231.1, }, /* 40 Mhz */ { 432.0, /* SGI */ 480.0, }, }, /* MCS 30 */ { /* 20 Mhz */ { 234.0, /* SGI */ 260.0, }, /* 40 Mhz */ { 486.0, /* SGI */ 540.0, }, }, /* MCS 31 */ { /* 20 Mhz */ { 260.0, /* SGI */ 288.9, }, /* 40 Mhz */ { 540.0, /* SGI */ 600.0, }, }, /* MCS 32 */ { /* 20 Mhz */ { 0.0, /* SGI */ 0.0, }, /* not valid */ /* 40 Mhz */ { 6.0, /* SGI */ 6.7, }, }, /* MCS 33 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 34 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 35 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 36 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 37 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 38 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 39 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 40 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 41 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 42 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 43 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 44 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 45 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 46 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 47 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 48 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 49 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 50 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 51 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 52 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 53 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 54 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 55 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 56 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 57 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 58 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 59 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 60 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 61 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 62 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 63 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 64 */ { /* 20 Mhz */ { 143.0, /* SGI */ 158.9, }, /* 40 Mhz */ { 297.0, /* SGI */ 330.0, }, }, /* MCS 65 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 66 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 67 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 68 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 69 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 70 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 71 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 72 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 73 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 74 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 75 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 76 */ { /* 20 Mhz */ { 214.5, /* SGI */ 238.3, }, /* 40 Mhz */ { 445.5, /* SGI */ 495.0, }, }, }; static const char *auth_alg_text[]={"Open System","Shared Key","EAP"}; #define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0]) static const char *status_text[] = { "Successful", /* 0 */ "Unspecified failure", /* 1 */ "Reserved", /* 2 */ "Reserved", /* 3 */ "Reserved", /* 4 */ "Reserved", /* 5 */ "Reserved", /* 6 */ "Reserved", /* 7 */ "Reserved", /* 8 */ "Reserved", /* 9 */ "Cannot Support all requested capabilities in the Capability " "Information field", /* 10 */ "Reassociation denied due to inability to confirm that association " "exists", /* 11 */ "Association denied due to reason outside the scope of the " "standard", /* 12 */ "Responding station does not support the specified authentication " "algorithm ", /* 13 */ "Received an Authentication frame with authentication transaction " "sequence number out of expected sequence", /* 14 */ "Authentication rejected because of challenge failure", /* 15 */ "Authentication rejected due to timeout waiting for next frame in " "sequence", /* 16 */ "Association denied because AP is unable to handle additional" "associated stations", /* 17 */ "Association denied due to requesting station not supporting all of " "the data rates in BSSBasicRateSet parameter", /* 18 */ "Association denied due to requesting station not supporting " "short preamble operation", /* 19 */ "Association denied due to requesting station not supporting " "PBCC encoding", /* 20 */ "Association denied due to requesting station not supporting " "channel agility", /* 21 */ "Association request rejected because Spectrum Management " "capability is required", /* 22 */ "Association request rejected because the information in the " "Power Capability element is unacceptable", /* 23 */ "Association request rejected because the information in the " "Supported Channels element is unacceptable", /* 24 */ "Association denied due to requesting station not supporting " "short slot operation", /* 25 */ "Association denied due to requesting station not supporting " "DSSS-OFDM operation", /* 26 */ "Association denied because the requested STA does not support HT " "features", /* 27 */ "Reserved", /* 28 */ "Association denied because the requested STA does not support " "the PCO transition time required by the AP", /* 29 */ "Reserved", /* 30 */ "Reserved", /* 31 */ "Unspecified, QoS-related failure", /* 32 */ "Association denied due to QAP having insufficient bandwidth " "to handle another QSTA", /* 33 */ "Association denied due to excessive frame loss rates and/or " "poor conditions on current operating channel", /* 34 */ "Association (with QBSS) denied due to requesting station not " "supporting the QoS facility", /* 35 */ "Association denied due to requesting station not supporting " "Block Ack", /* 36 */ "The request has been declined", /* 37 */ "The request has not been successful as one or more parameters " "have invalid values", /* 38 */ "The TS has not been created because the request cannot be honored. " "Try again with the suggested changes to the TSPEC", /* 39 */ "Invalid Information Element", /* 40 */ "Group Cipher is not valid", /* 41 */ "Pairwise Cipher is not valid", /* 42 */ "AKMP is not valid", /* 43 */ "Unsupported RSN IE version", /* 44 */ "Invalid RSN IE Capabilities", /* 45 */ "Cipher suite is rejected per security policy", /* 46 */ "The TS has not been created. However, the HC may be capable of " "creating a TS, in response to a request, after the time indicated " "in the TS Delay element", /* 47 */ "Direct Link is not allowed in the BSS by policy", /* 48 */ "Destination STA is not present within this QBSS.", /* 49 */ "The Destination STA is not a QSTA.", /* 50 */ }; #define NUM_STATUSES (sizeof status_text / sizeof status_text[0]) static const char *reason_text[] = { "Reserved", /* 0 */ "Unspecified reason", /* 1 */ "Previous authentication no longer valid", /* 2 */ "Deauthenticated because sending station is leaving (or has left) " "IBSS or ESS", /* 3 */ "Disassociated due to inactivity", /* 4 */ "Disassociated because AP is unable to handle all currently " " associated stations", /* 5 */ "Class 2 frame received from nonauthenticated station", /* 6 */ "Class 3 frame received from nonassociated station", /* 7 */ "Disassociated because sending station is leaving " "(or has left) BSS", /* 8 */ "Station requesting (re)association is not authenticated with " "responding station", /* 9 */ "Disassociated because the information in the Power Capability " "element is unacceptable", /* 10 */ "Disassociated because the information in the SupportedChannels " "element is unacceptable", /* 11 */ "Invalid Information Element", /* 12 */ "Reserved", /* 13 */ "Michael MIC failure", /* 14 */ "4-Way Handshake timeout", /* 15 */ "Group key update timeout", /* 16 */ "Information element in 4-Way Handshake different from (Re)Association" "Request/Probe Response/Beacon", /* 17 */ "Group Cipher is not valid", /* 18 */ "AKMP is not valid", /* 20 */ "Unsupported RSN IE version", /* 21 */ "Invalid RSN IE Capabilities", /* 22 */ "IEEE 802.1X Authentication failed", /* 23 */ "Cipher suite is rejected per security policy", /* 24 */ "Reserved", /* 25 */ "Reserved", /* 26 */ "Reserved", /* 27 */ "Reserved", /* 28 */ "Reserved", /* 29 */ "Reserved", /* 30 */ "TS deleted because QoS AP lacks sufficient bandwidth for this " "QoS STA due to a change in BSS service characteristics or " "operational mode (e.g. an HT BSS change from 40 MHz channel " "to 20 MHz channel)", /* 31 */ "Disassociated for unspecified, QoS-related reason", /* 32 */ "Disassociated because QoS AP lacks sufficient bandwidth for this " "QoS STA", /* 33 */ "Disassociated because of excessive number of frames that need to be " "acknowledged, but are not acknowledged for AP transmissions " "and/or poor channel conditions", /* 34 */ "Disassociated because STA is transmitting outside the limits " "of its TXOPs", /* 35 */ "Requested from peer STA as the STA is leaving the BSS " "(or resetting)", /* 36 */ "Requested from peer STA as it does not want to use the " "mechanism", /* 37 */ "Requested from peer STA as the STA received frames using the " "mechanism for which a set up is required", /* 38 */ "Requested from peer STA due to time out", /* 39 */ "Reserved", /* 40 */ "Reserved", /* 41 */ "Reserved", /* 42 */ "Reserved", /* 43 */ "Reserved", /* 44 */ "Peer STA does not support the requested cipher suite", /* 45 */ "Association denied due to requesting STA not supporting HT " "features", /* 46 */ }; #define NUM_REASONS (sizeof reason_text / sizeof reason_text[0]) static int wep_print(netdissect_options *ndo, const u_char *p) { uint32_t iv; if (!ND_TTEST2(*p, IEEE802_11_IV_LEN + IEEE802_11_KID_LEN)) return 0; iv = EXTRACT_LE_32BITS(p); ND_PRINT((ndo, " IV:%3x Pad %x KeyID %x", IV_IV(iv), IV_PAD(iv), IV_KEYID(iv))); return 1; } static int parse_elements(netdissect_options *ndo, struct mgmt_body_t *pbody, const u_char *p, int offset, u_int length) { u_int elementlen; struct ssid_t ssid; struct challenge_t challenge; struct rates_t rates; struct ds_t ds; struct cf_t cf; struct tim_t tim; /* * We haven't seen any elements yet. */ pbody->challenge_present = 0; pbody->ssid_present = 0; pbody->rates_present = 0; pbody->ds_present = 0; pbody->cf_present = 0; pbody->tim_present = 0; while (length != 0) { /* Make sure we at least have the element ID and length. */ if (!ND_TTEST2(*(p + offset), 2)) return 0; if (length < 2) return 0; elementlen = *(p + offset + 1); /* Make sure we have the entire element. */ if (!ND_TTEST2(*(p + offset + 2), elementlen)) return 0; if (length < elementlen + 2) return 0; switch (*(p + offset)) { case E_SSID: memcpy(&ssid, p + offset, 2); offset += 2; length -= 2; if (ssid.length != 0) { if (ssid.length > sizeof(ssid.ssid) - 1) return 0; if (!ND_TTEST2(*(p + offset), ssid.length)) return 0; if (length < ssid.length) return 0; memcpy(&ssid.ssid, p + offset, ssid.length); offset += ssid.length; length -= ssid.length; } ssid.ssid[ssid.length] = '\0'; /* * Present and not truncated. * * If we haven't already seen an SSID IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->ssid_present) { pbody->ssid = ssid; pbody->ssid_present = 1; } break; case E_CHALLENGE: memcpy(&challenge, p + offset, 2); offset += 2; length -= 2; if (challenge.length != 0) { if (challenge.length > sizeof(challenge.text) - 1) return 0; if (!ND_TTEST2(*(p + offset), challenge.length)) return 0; if (length < challenge.length) return 0; memcpy(&challenge.text, p + offset, challenge.length); offset += challenge.length; length -= challenge.length; } challenge.text[challenge.length] = '\0'; /* * Present and not truncated. * * If we haven't already seen a challenge IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->challenge_present) { pbody->challenge = challenge; pbody->challenge_present = 1; } break; case E_RATES: memcpy(&rates, p + offset, 2); offset += 2; length -= 2; if (rates.length != 0) { if (rates.length > sizeof rates.rate) return 0; if (!ND_TTEST2(*(p + offset), rates.length)) return 0; if (length < rates.length) return 0; memcpy(&rates.rate, p + offset, rates.length); offset += rates.length; length -= rates.length; } /* * Present and not truncated. * * If we haven't already seen a rates IE, * copy this one if it's not zero-length, * otherwise ignore this one, so we later * report the first one we saw. * * We ignore zero-length rates IEs as some * devices seem to put a zero-length rates * IE, followed by an SSID IE, followed by * a non-zero-length rates IE into frames, * even though IEEE Std 802.11-2007 doesn't * seem to indicate that a zero-length rates * IE is valid. */ if (!pbody->rates_present && rates.length != 0) { pbody->rates = rates; pbody->rates_present = 1; } break; case E_DS: memcpy(&ds, p + offset, 2); offset += 2; length -= 2; if (ds.length != 1) { offset += ds.length; length -= ds.length; break; } ds.channel = *(p + offset); offset += 1; length -= 1; /* * Present and not truncated. * * If we haven't already seen a DS IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->ds_present) { pbody->ds = ds; pbody->ds_present = 1; } break; case E_CF: memcpy(&cf, p + offset, 2); offset += 2; length -= 2; if (cf.length != 6) { offset += cf.length; length -= cf.length; break; } memcpy(&cf.count, p + offset, 6); offset += 6; length -= 6; /* * Present and not truncated. * * If we haven't already seen a CF IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->cf_present) { pbody->cf = cf; pbody->cf_present = 1; } break; case E_TIM: memcpy(&tim, p + offset, 2); offset += 2; length -= 2; if (tim.length <= 3) { offset += tim.length; length -= tim.length; break; } if (tim.length - 3 > (int)sizeof tim.bitmap) return 0; memcpy(&tim.count, p + offset, 3); offset += 3; length -= 3; memcpy(tim.bitmap, p + offset + 3, tim.length - 3); offset += tim.length - 3; length -= tim.length - 3; /* * Present and not truncated. * * If we haven't already seen a TIM IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->tim_present) { pbody->tim = tim; pbody->tim_present = 1; } break; default: #if 0 ND_PRINT((ndo, "(1) unhandled element_id (%d) ", *(p + offset))); #endif offset += 2 + elementlen; length -= 2 + elementlen; break; } } /* No problems found. */ return 1; } /********************************************************************************* * Print Handle functions for the management frame types *********************************************************************************/ static int handle_beacon(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; length -= IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; length -= IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); ND_PRINT((ndo, " %s", CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS")); PRINT_DS_CHANNEL(pbody); return ret; } static int handle_assoc_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; length -= IEEE802_11_LISTENINT_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); return ret; } static int handle_assoc_response(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.status_code = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_STATUS_LEN; length -= IEEE802_11_STATUS_LEN; pbody.aid = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_AID_LEN; length -= IEEE802_11_AID_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); ND_PRINT((ndo, " AID(%x) :%s: %s", ((uint16_t)(pbody.aid << 2 )) >> 2 , CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "", (pbody.status_code < NUM_STATUSES ? status_text[pbody.status_code] : "n/a"))); return ret; } static int handle_reassoc_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; length -= IEEE802_11_LISTENINT_LEN; memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN); offset += IEEE802_11_AP_LEN; length -= IEEE802_11_AP_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); ND_PRINT((ndo, " AP : %s", etheraddr_string(ndo, pbody.ap ))); return ret; } static int handle_reassoc_response(netdissect_options *ndo, const u_char *p, u_int length) { /* Same as a Association Reponse */ return handle_assoc_response(ndo, p, length); } static int handle_probe_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); return ret; } static int handle_probe_response(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; length -= IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; length -= IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); PRINT_DS_CHANNEL(pbody); return ret; } static int handle_atim(void) { /* the frame body for ATIM is null. */ return 1; } static int handle_disassoc(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; if (length < IEEE802_11_REASON_LEN) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); ND_PRINT((ndo, ": %s", (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved")); return 1; } static int handle_auth(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, 6)) return 0; if (length < 6) return 0; pbody.auth_alg = EXTRACT_LE_16BITS(p); offset += 2; length -= 2; pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset); offset += 2; length -= 2; pbody.status_code = EXTRACT_LE_16BITS(p + offset); offset += 2; length -= 2; ret = parse_elements(ndo, &pbody, p, offset, length); if ((pbody.auth_alg == 1) && ((pbody.auth_trans_seq_num == 2) || (pbody.auth_trans_seq_num == 3))) { ND_PRINT((ndo, " (%s)-%x [Challenge Text] %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, ((pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : ""))); return ret; } ND_PRINT((ndo, " (%s)-%x: %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, (pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : "")); return ret; } static int handle_deauth(netdissect_options *ndo, const uint8_t *src, const u_char *p, u_int length) { struct mgmt_body_t pbody; const char *reason = NULL; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; if (length < IEEE802_11_REASON_LEN) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); reason = (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved"; if (ndo->ndo_eflag) { ND_PRINT((ndo, ": %s", reason)); } else { ND_PRINT((ndo, " (%s): %s", etheraddr_string(ndo, src), reason)); } return 1; } #define PRINT_HT_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "TxChWidth")) : \ (v) == 1 ? ND_PRINT((ndo, "MIMOPwrSave")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_BA_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "ADDBA Request")) : \ (v) == 1 ? ND_PRINT((ndo, "ADDBA Response")) : \ (v) == 2 ? ND_PRINT((ndo, "DELBA")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHLINK_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Request")) : \ (v) == 1 ? ND_PRINT((ndo, "Report")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHPEERING_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Open")) : \ (v) == 1 ? ND_PRINT((ndo, "Confirm")) : \ (v) == 2 ? ND_PRINT((ndo, "Close")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHPATH_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Request")) : \ (v) == 1 ? ND_PRINT((ndo, "Report")) : \ (v) == 2 ? ND_PRINT((ndo, "Error")) : \ (v) == 3 ? ND_PRINT((ndo, "RootAnnouncement")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESH_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "MeshLink")) : \ (v) == 1 ? ND_PRINT((ndo, "HWMP")) : \ (v) == 2 ? ND_PRINT((ndo, "Gate Announcement")) : \ (v) == 3 ? ND_PRINT((ndo, "Congestion Control")) : \ (v) == 4 ? ND_PRINT((ndo, "MCCA Setup Request")) : \ (v) == 5 ? ND_PRINT((ndo, "MCCA Setup Reply")) : \ (v) == 6 ? ND_PRINT((ndo, "MCCA Advertisement Request")) : \ (v) == 7 ? ND_PRINT((ndo, "MCCA Advertisement")) : \ (v) == 8 ? ND_PRINT((ndo, "MCCA Teardown")) : \ (v) == 9 ? ND_PRINT((ndo, "TBTT Adjustment Request")) : \ (v) == 10 ? ND_PRINT((ndo, "TBTT Adjustment Response")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MULTIHOP_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Proxy Update")) : \ (v) == 1 ? ND_PRINT((ndo, "Proxy Update Confirmation")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_SELFPROT_ACTION(v) (\ (v) == 1 ? ND_PRINT((ndo, "Peering Open")) : \ (v) == 2 ? ND_PRINT((ndo, "Peering Confirm")) : \ (v) == 3 ? ND_PRINT((ndo, "Peering Close")) : \ (v) == 4 ? ND_PRINT((ndo, "Group Key Inform")) : \ (v) == 5 ? ND_PRINT((ndo, "Group Key Acknowledge")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) static int handle_action(netdissect_options *ndo, const uint8_t *src, const u_char *p, u_int length) { if (!ND_TTEST2(*p, 2)) return 0; if (length < 2) return 0; if (ndo->ndo_eflag) { ND_PRINT((ndo, ": ")); } else { ND_PRINT((ndo, " (%s): ", etheraddr_string(ndo, src))); } switch (p[0]) { case 0: ND_PRINT((ndo, "Spectrum Management Act#%d", p[1])); break; case 1: ND_PRINT((ndo, "QoS Act#%d", p[1])); break; case 2: ND_PRINT((ndo, "DLS Act#%d", p[1])); break; case 3: ND_PRINT((ndo, "BA ")); PRINT_BA_ACTION(p[1]); break; case 7: ND_PRINT((ndo, "HT ")); PRINT_HT_ACTION(p[1]); break; case 13: ND_PRINT((ndo, "MeshAction ")); PRINT_MESH_ACTION(p[1]); break; case 14: ND_PRINT((ndo, "MultiohopAction ")); PRINT_MULTIHOP_ACTION(p[1]); break; case 15: ND_PRINT((ndo, "SelfprotectAction ")); PRINT_SELFPROT_ACTION(p[1]); break; case 127: ND_PRINT((ndo, "Vendor Act#%d", p[1])); break; default: ND_PRINT((ndo, "Reserved(%d) Act#%d", p[0], p[1])); break; } return 1; } /********************************************************************************* * Print Body funcs *********************************************************************************/ static int mgmt_body_print(netdissect_options *ndo, uint16_t fc, const uint8_t *src, const u_char *p, u_int length) { ND_PRINT((ndo, "%s", tok2str(st_str, "Unhandled Management subtype(%x)", FC_SUBTYPE(fc)))); /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) return wep_print(ndo, p); switch (FC_SUBTYPE(fc)) { case ST_ASSOC_REQUEST: return handle_assoc_request(ndo, p, length); case ST_ASSOC_RESPONSE: return handle_assoc_response(ndo, p, length); case ST_REASSOC_REQUEST: return handle_reassoc_request(ndo, p, length); case ST_REASSOC_RESPONSE: return handle_reassoc_response(ndo, p, length); case ST_PROBE_REQUEST: return handle_probe_request(ndo, p, length); case ST_PROBE_RESPONSE: return handle_probe_response(ndo, p, length); case ST_BEACON: return handle_beacon(ndo, p, length); case ST_ATIM: return handle_atim(); case ST_DISASSOC: return handle_disassoc(ndo, p, length); case ST_AUTH: return handle_auth(ndo, p, length); case ST_DEAUTH: return handle_deauth(ndo, src, p, length); case ST_ACTION: return handle_action(ndo, src, p, length); default: return 1; } } /********************************************************************************* * Handles printing all the control frame types *********************************************************************************/ static int ctrl_body_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc)))); switch (FC_SUBTYPE(fc)) { case CTRL_CONTROL_WRAPPER: /* XXX - requires special handling */ break; case CTRL_BAR: if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ", etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq)))); break; case CTRL_BA: if (!ND_TTEST2(*p, CTRL_BA_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra))); break; case CTRL_PS_POLL: if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN)) return 0; ND_PRINT((ndo, " AID(%x)", EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid)))); break; case CTRL_RTS: if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " TA:%s ", etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta))); break; case CTRL_CTS: if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra))); break; case CTRL_ACK: if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra))); break; case CTRL_CF_END: if (!ND_TTEST2(*p, CTRL_END_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra))); break; case CTRL_END_ACK: if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra))); break; } return 1; } /* * Data Frame - Address field contents * * To Ds | From DS | Addr 1 | Addr 2 | Addr 3 | Addr 4 * 0 | 0 | DA | SA | BSSID | n/a * 0 | 1 | DA | BSSID | SA | n/a * 1 | 0 | BSSID | SA | DA | n/a * 1 | 1 | RA | TA | DA | SA */ /* * Function to get source and destination MAC addresses for a data frame. */ static void get_data_src_dst_mac(uint16_t fc, const u_char *p, const uint8_t **srcp, const uint8_t **dstp) { #define ADDR1 (p + 4) #define ADDR2 (p + 10) #define ADDR3 (p + 16) #define ADDR4 (p + 24) if (!FC_TO_DS(fc)) { if (!FC_FROM_DS(fc)) { /* not To DS and not From DS */ *srcp = ADDR2; *dstp = ADDR1; } else { /* not To DS and From DS */ *srcp = ADDR3; *dstp = ADDR1; } } else { if (!FC_FROM_DS(fc)) { /* From DS and not To DS */ *srcp = ADDR2; *dstp = ADDR3; } else { /* To DS and From DS */ *srcp = ADDR4; *dstp = ADDR3; } } #undef ADDR1 #undef ADDR2 #undef ADDR3 #undef ADDR4 } static void get_mgmt_src_dst_mac(const u_char *p, const uint8_t **srcp, const uint8_t **dstp) { const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p; if (srcp != NULL) *srcp = hp->sa; if (dstp != NULL) *dstp = hp->da; } /* * Print Header funcs */ static void data_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { u_int subtype = FC_SUBTYPE(fc); if (DATA_FRAME_IS_CF_ACK(subtype) || DATA_FRAME_IS_CF_POLL(subtype) || DATA_FRAME_IS_QOS(subtype)) { ND_PRINT((ndo, "CF ")); if (DATA_FRAME_IS_CF_ACK(subtype)) { if (DATA_FRAME_IS_CF_POLL(subtype)) ND_PRINT((ndo, "Ack/Poll")); else ND_PRINT((ndo, "Ack")); } else { if (DATA_FRAME_IS_CF_POLL(subtype)) ND_PRINT((ndo, "Poll")); } if (DATA_FRAME_IS_QOS(subtype)) ND_PRINT((ndo, "+QoS")); ND_PRINT((ndo, " ")); } #define ADDR1 (p + 4) #define ADDR2 (p + 10) #define ADDR3 (p + 16) #define ADDR4 (p + 24) if (!FC_TO_DS(fc) && !FC_FROM_DS(fc)) { ND_PRINT((ndo, "DA:%s SA:%s BSSID:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (!FC_TO_DS(fc) && FC_FROM_DS(fc)) { ND_PRINT((ndo, "DA:%s BSSID:%s SA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (FC_TO_DS(fc) && !FC_FROM_DS(fc)) { ND_PRINT((ndo, "BSSID:%s SA:%s DA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) { ND_PRINT((ndo, "RA:%s TA:%s DA:%s SA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3), etheraddr_string(ndo, ADDR4))); } #undef ADDR1 #undef ADDR2 #undef ADDR3 #undef ADDR4 } static void mgmt_header_print(netdissect_options *ndo, const u_char *p) { const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p; ND_PRINT((ndo, "BSSID:%s DA:%s SA:%s ", etheraddr_string(ndo, (hp)->bssid), etheraddr_string(ndo, (hp)->da), etheraddr_string(ndo, (hp)->sa))); } static void ctrl_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { switch (FC_SUBTYPE(fc)) { case CTRL_BAR: ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ", etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq)))); break; case CTRL_BA: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra))); break; case CTRL_PS_POLL: ND_PRINT((ndo, "BSSID:%s TA:%s ", etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->bssid), etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->ta))); break; case CTRL_RTS: ND_PRINT((ndo, "RA:%s TA:%s ", etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta))); break; case CTRL_CTS: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra))); break; case CTRL_ACK: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra))); break; case CTRL_CF_END: ND_PRINT((ndo, "RA:%s BSSID:%s ", etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->bssid))); break; case CTRL_END_ACK: ND_PRINT((ndo, "RA:%s BSSID:%s ", etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->bssid))); break; default: /* We shouldn't get here - we should already have quit */ break; } } static int extract_header_length(netdissect_options *ndo, uint16_t fc) { int len; switch (FC_TYPE(fc)) { case T_MGMT: return MGMT_HDRLEN; case T_CTRL: switch (FC_SUBTYPE(fc)) { case CTRL_CONTROL_WRAPPER: return CTRL_CONTROL_WRAPPER_HDRLEN; case CTRL_BAR: return CTRL_BAR_HDRLEN; case CTRL_BA: return CTRL_BA_HDRLEN; case CTRL_PS_POLL: return CTRL_PS_POLL_HDRLEN; case CTRL_RTS: return CTRL_RTS_HDRLEN; case CTRL_CTS: return CTRL_CTS_HDRLEN; case CTRL_ACK: return CTRL_ACK_HDRLEN; case CTRL_CF_END: return CTRL_END_HDRLEN; case CTRL_END_ACK: return CTRL_END_ACK_HDRLEN; default: ND_PRINT((ndo, "unknown 802.11 ctrl frame subtype (%d)", FC_SUBTYPE(fc))); return 0; } case T_DATA: len = (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24; if (DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) len += 2; return len; default: ND_PRINT((ndo, "unknown 802.11 frame type (%d)", FC_TYPE(fc))); return 0; } } static int extract_mesh_header_length(const u_char *p) { return (p[0] &~ 3) ? 0 : 6*(1 + (p[0] & 3)); } /* * Print the 802.11 MAC header. */ static void ieee_802_11_hdr_print(netdissect_options *ndo, uint16_t fc, const u_char *p, u_int hdrlen, u_int meshdrlen) { if (ndo->ndo_vflag) { if (FC_MORE_DATA(fc)) ND_PRINT((ndo, "More Data ")); if (FC_MORE_FLAG(fc)) ND_PRINT((ndo, "More Fragments ")); if (FC_POWER_MGMT(fc)) ND_PRINT((ndo, "Pwr Mgmt ")); if (FC_RETRY(fc)) ND_PRINT((ndo, "Retry ")); if (FC_ORDER(fc)) ND_PRINT((ndo, "Strictly Ordered ")); if (FC_PROTECTED(fc)) ND_PRINT((ndo, "Protected ")); if (FC_TYPE(fc) != T_CTRL || FC_SUBTYPE(fc) != CTRL_PS_POLL) ND_PRINT((ndo, "%dus ", EXTRACT_LE_16BITS( &((const struct mgmt_header_t *)p)->duration))); } if (meshdrlen != 0) { const struct meshcntl_t *mc = (const struct meshcntl_t *)&p[hdrlen - meshdrlen]; int ae = mc->flags & 3; ND_PRINT((ndo, "MeshData (AE %d TTL %u seq %u", ae, mc->ttl, EXTRACT_LE_32BITS(mc->seq))); if (ae > 0) ND_PRINT((ndo, " A4:%s", etheraddr_string(ndo, mc->addr4))); if (ae > 1) ND_PRINT((ndo, " A5:%s", etheraddr_string(ndo, mc->addr5))); if (ae > 2) ND_PRINT((ndo, " A6:%s", etheraddr_string(ndo, mc->addr6))); ND_PRINT((ndo, ") ")); } switch (FC_TYPE(fc)) { case T_MGMT: mgmt_header_print(ndo, p); break; case T_CTRL: ctrl_header_print(ndo, fc, p); break; case T_DATA: data_header_print(ndo, fc, p); break; default: break; } } #ifndef roundup2 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ #endif static const char tstr[] = "[|802.11]"; static u_int ieee802_11_print(netdissect_options *ndo, const u_char *p, u_int length, u_int orig_caplen, int pad, u_int fcslen) { uint16_t fc; u_int caplen, hdrlen, meshdrlen; struct lladdr_info src, dst; int llc_hdrlen; caplen = orig_caplen; /* Remove FCS, if present */ if (length < fcslen) { ND_PRINT((ndo, "%s", tstr)); return caplen; } length -= fcslen; if (caplen > length) { /* Amount of FCS in actual packet data, if any */ fcslen = caplen - length; caplen -= fcslen; ndo->ndo_snapend -= fcslen; } if (caplen < IEEE802_11_FC_LEN) { ND_PRINT((ndo, "%s", tstr)); return orig_caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(ndo, fc); if (hdrlen == 0) { /* Unknown frame type or control frame subtype; quit. */ return (0); } if (pad) hdrlen = roundup2(hdrlen, 4); if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA && DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) { meshdrlen = extract_mesh_header_length(p+hdrlen); hdrlen += meshdrlen; } else meshdrlen = 0; if (caplen < hdrlen) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } if (ndo->ndo_eflag) ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen); /* * Go past the 802.11 header. */ length -= hdrlen; caplen -= hdrlen; p += hdrlen; src.addr_string = etheraddr_string; dst.addr_string = etheraddr_string; switch (FC_TYPE(fc)) { case T_MGMT: get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr); if (!mgmt_body_print(ndo, fc, src.addr, p, length)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_CTRL: if (!ctrl_body_print(ndo, fc, p - hdrlen)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_DATA: if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc))) return hdrlen; /* no-data frame */ /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) { ND_PRINT((ndo, "Data")); if (!wep_print(ndo, p)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } } else { get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr); llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* * Some kinds of LLC packet we cannot * handle intelligently */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } break; default: /* We shouldn't get here - we should already have quit */ break; } return hdrlen; } /* * This is the top level routine of the printer. 'p' points * to the 802.11 header of the packet, 'h->ts' is the timestamp, * 'h->len' is the length of the packet off the wire, and 'h->caplen' * is the number of bytes actually captured. */ u_int ieee802_11_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_print(ndo, p, h->len, h->caplen, 0, 0); } /* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */ /* NetBSD: ieee802_11_radio.h,v 1.2 2006/02/26 03:04:03 dyoung Exp */ /*- * Copyright (c) 2003, 2004 David Young. 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. The name of David Young may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``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 DAVID * YOUNG 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. */ /* A generic radio capture format is desirable. It must be * rigidly defined (e.g., units for fields should be given), * and easily extensible. * * The following is an extensible radio capture format. It is * based on a bitmap indicating which fields are present. * * I am trying to describe precisely what the application programmer * should expect in the following, and for that reason I tell the * units and origin of each measurement (where it applies), or else I * use sufficiently weaselly language ("is a monotonically nondecreasing * function of...") that I cannot set false expectations for lawyerly * readers. */ /* * The radio capture header precedes the 802.11 header. * * Note well: all radiotap fields are little-endian. */ struct ieee80211_radiotap_header { uint8_t it_version; /* Version 0. Only increases * for drastic changes, * introduction of compatible * new fields does not count. */ uint8_t it_pad; uint16_t it_len; /* length of the whole * header in bytes, including * it_version, it_pad, * it_len, and data fields. */ uint32_t it_present; /* A bitmap telling which * fields are present. Set bit 31 * (0x80000000) to extend the * bitmap by another 32 bits. * Additional extensions are made * by setting bit 31. */ }; /* Name Data type Units * ---- --------- ----- * * IEEE80211_RADIOTAP_TSFT uint64_t microseconds * * Value in microseconds of the MAC's 64-bit 802.11 Time * Synchronization Function timer when the first bit of the * MPDU arrived at the MAC. For received frames, only. * * IEEE80211_RADIOTAP_CHANNEL 2 x uint16_t MHz, bitmap * * Tx/Rx frequency in MHz, followed by flags (see below). * Note that IEEE80211_RADIOTAP_XCHANNEL must be used to * represent an HT channel as there is not enough room in * the flags word. * * IEEE80211_RADIOTAP_FHSS uint16_t see below * * For frequency-hopping radios, the hop set (first byte) * and pattern (second byte). * * IEEE80211_RADIOTAP_RATE uint8_t 500kb/s or index * * Tx/Rx data rate. If bit 0x80 is set then it represents an * an MCS index and not an IEEE rate. * * IEEE80211_RADIOTAP_DBM_ANTSIGNAL int8_t decibels from * one milliwatt (dBm) * * RF signal power at the antenna, decibel difference from * one milliwatt. * * IEEE80211_RADIOTAP_DBM_ANTNOISE int8_t decibels from * one milliwatt (dBm) * * RF noise power at the antenna, decibel difference from one * milliwatt. * * IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB) * * RF signal power at the antenna, decibel difference from an * arbitrary, fixed reference. * * IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB) * * RF noise power at the antenna, decibel difference from an * arbitrary, fixed reference point. * * IEEE80211_RADIOTAP_LOCK_QUALITY uint16_t unitless * * Quality of Barker code lock. Unitless. Monotonically * nondecreasing with "better" lock strength. Called "Signal * Quality" in datasheets. (Is there a standard way to measure * this?) * * IEEE80211_RADIOTAP_TX_ATTENUATION uint16_t unitless * * Transmit power expressed as unitless distance from max * power set at factory calibration. 0 is max power. * Monotonically nondecreasing with lower power levels. * * IEEE80211_RADIOTAP_DB_TX_ATTENUATION uint16_t decibels (dB) * * Transmit power expressed as decibel distance from max power * set at factory calibration. 0 is max power. Monotonically * nondecreasing with lower power levels. * * IEEE80211_RADIOTAP_DBM_TX_POWER int8_t decibels from * one milliwatt (dBm) * * Transmit power expressed as dBm (decibels from a 1 milliwatt * reference). This is the absolute power level measured at * the antenna port. * * IEEE80211_RADIOTAP_FLAGS uint8_t bitmap * * Properties of transmitted and received frames. See flags * defined below. * * IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index * * Unitless indication of the Rx/Tx antenna for this packet. * The first antenna is antenna 0. * * IEEE80211_RADIOTAP_RX_FLAGS uint16_t bitmap * * Properties of received frames. See flags defined below. * * IEEE80211_RADIOTAP_XCHANNEL uint32_t bitmap * uint16_t MHz * uint8_t channel number * uint8_t .5 dBm * * Extended channel specification: flags (see below) followed by * frequency in MHz, the corresponding IEEE channel number, and * finally the maximum regulatory transmit power cap in .5 dBm * units. This property supersedes IEEE80211_RADIOTAP_CHANNEL * and only one of the two should be present. * * IEEE80211_RADIOTAP_MCS uint8_t known * uint8_t flags * uint8_t mcs * * Bitset indicating which fields have known values, followed * by bitset of flag values, followed by the MCS rate index as * in IEEE 802.11n. * * * IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitless * * Contains the AMPDU information for the subframe. * * IEEE80211_RADIOTAP_VHT u16, u8, u8, u8[4], u8, u8, u16 * * Contains VHT information about this frame. * * IEEE80211_RADIOTAP_VENDOR_NAMESPACE * uint8_t OUI[3] * uint8_t subspace * uint16_t length * * The Vendor Namespace Field contains three sub-fields. The first * sub-field is 3 bytes long. It contains the vendor's IEEE 802 * Organizationally Unique Identifier (OUI). The fourth byte is a * vendor-specific "namespace selector." * */ enum ieee80211_radiotap_type { IEEE80211_RADIOTAP_TSFT = 0, IEEE80211_RADIOTAP_FLAGS = 1, IEEE80211_RADIOTAP_RATE = 2, IEEE80211_RADIOTAP_CHANNEL = 3, IEEE80211_RADIOTAP_FHSS = 4, IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5, IEEE80211_RADIOTAP_DBM_ANTNOISE = 6, IEEE80211_RADIOTAP_LOCK_QUALITY = 7, IEEE80211_RADIOTAP_TX_ATTENUATION = 8, IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9, IEEE80211_RADIOTAP_DBM_TX_POWER = 10, IEEE80211_RADIOTAP_ANTENNA = 11, IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12, IEEE80211_RADIOTAP_DB_ANTNOISE = 13, IEEE80211_RADIOTAP_RX_FLAGS = 14, /* NB: gap for netbsd definitions */ IEEE80211_RADIOTAP_XCHANNEL = 18, IEEE80211_RADIOTAP_MCS = 19, IEEE80211_RADIOTAP_AMPDU_STATUS = 20, IEEE80211_RADIOTAP_VHT = 21, IEEE80211_RADIOTAP_NAMESPACE = 29, IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30, IEEE80211_RADIOTAP_EXT = 31 }; /* channel attributes */ #define IEEE80211_CHAN_TURBO 0x00010 /* Turbo channel */ #define IEEE80211_CHAN_CCK 0x00020 /* CCK channel */ #define IEEE80211_CHAN_OFDM 0x00040 /* OFDM channel */ #define IEEE80211_CHAN_2GHZ 0x00080 /* 2 GHz spectrum channel. */ #define IEEE80211_CHAN_5GHZ 0x00100 /* 5 GHz spectrum channel */ #define IEEE80211_CHAN_PASSIVE 0x00200 /* Only passive scan allowed */ #define IEEE80211_CHAN_DYN 0x00400 /* Dynamic CCK-OFDM channel */ #define IEEE80211_CHAN_GFSK 0x00800 /* GFSK channel (FHSS PHY) */ #define IEEE80211_CHAN_GSM 0x01000 /* 900 MHz spectrum channel */ #define IEEE80211_CHAN_STURBO 0x02000 /* 11a static turbo channel only */ #define IEEE80211_CHAN_HALF 0x04000 /* Half rate channel */ #define IEEE80211_CHAN_QUARTER 0x08000 /* Quarter rate channel */ #define IEEE80211_CHAN_HT20 0x10000 /* HT 20 channel */ #define IEEE80211_CHAN_HT40U 0x20000 /* HT 40 channel w/ ext above */ #define IEEE80211_CHAN_HT40D 0x40000 /* HT 40 channel w/ ext below */ /* Useful combinations of channel characteristics, borrowed from Ethereal */ #define IEEE80211_CHAN_A \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_B \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK) #define IEEE80211_CHAN_G \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN) #define IEEE80211_CHAN_TA \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_TURBO) #define IEEE80211_CHAN_TG \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN | IEEE80211_CHAN_TURBO) /* For IEEE80211_RADIOTAP_FLAGS */ #define IEEE80211_RADIOTAP_F_CFP 0x01 /* sent/received * during CFP */ #define IEEE80211_RADIOTAP_F_SHORTPRE 0x02 /* sent/received * with short * preamble */ #define IEEE80211_RADIOTAP_F_WEP 0x04 /* sent/received * with WEP encryption */ #define IEEE80211_RADIOTAP_F_FRAG 0x08 /* sent/received * with fragmentation */ #define IEEE80211_RADIOTAP_F_FCS 0x10 /* frame includes FCS */ #define IEEE80211_RADIOTAP_F_DATAPAD 0x20 /* frame has padding between * 802.11 header and payload * (to 32-bit boundary) */ #define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* does not pass FCS check */ /* For IEEE80211_RADIOTAP_RX_FLAGS */ #define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */ #define IEEE80211_RADIOTAP_F_RX_PLCP_CRC 0x0002 /* frame failed PLCP CRC check */ /* For IEEE80211_RADIOTAP_MCS known */ #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN 0x01 #define IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN 0x02 /* MCS index field */ #define IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN 0x04 #define IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN 0x08 #define IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN 0x10 #define IEEE80211_RADIOTAP_MCS_STBC_KNOWN 0x20 #define IEEE80211_RADIOTAP_MCS_NESS_KNOWN 0x40 #define IEEE80211_RADIOTAP_MCS_NESS_BIT_1 0x80 /* For IEEE80211_RADIOTAP_MCS flags */ #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK 0x03 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20 0 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 1 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20L 2 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20U 3 #define IEEE80211_RADIOTAP_MCS_SHORT_GI 0x04 /* short guard interval */ #define IEEE80211_RADIOTAP_MCS_HT_GREENFIELD 0x08 #define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10 #define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60 #define IEEE80211_RADIOTAP_MCS_STBC_1 1 #define IEEE80211_RADIOTAP_MCS_STBC_2 2 #define IEEE80211_RADIOTAP_MCS_STBC_3 3 #define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5 #define IEEE80211_RADIOTAP_MCS_NESS_BIT_0 0x80 /* For IEEE80211_RADIOTAP_AMPDU_STATUS */ #define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001 #define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002 #define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004 #define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008 #define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010 #define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020 /* For IEEE80211_RADIOTAP_VHT known */ #define IEEE80211_RADIOTAP_VHT_STBC_KNOWN 0x0001 #define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA_KNOWN 0x0002 #define IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN 0x0004 #define IEEE80211_RADIOTAP_VHT_SGI_NSYM_DIS_KNOWN 0x0008 #define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM_KNOWN 0x0010 #define IEEE80211_RADIOTAP_VHT_BEAMFORMED_KNOWN 0x0020 #define IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN 0x0040 #define IEEE80211_RADIOTAP_VHT_GROUP_ID_KNOWN 0x0080 #define IEEE80211_RADIOTAP_VHT_PARTIAL_AID_KNOWN 0x0100 /* For IEEE80211_RADIOTAP_VHT flags */ #define IEEE80211_RADIOTAP_VHT_STBC 0x01 #define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA 0x02 #define IEEE80211_RADIOTAP_VHT_SHORT_GI 0x04 #define IEEE80211_RADIOTAP_VHT_SGI_NSYM_M10_9 0x08 #define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM 0x10 #define IEEE80211_RADIOTAP_VHT_BEAMFORMED 0x20 #define IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK 0x1f #define IEEE80211_RADIOTAP_VHT_NSS_MASK 0x0f #define IEEE80211_RADIOTAP_VHT_MCS_MASK 0xf0 #define IEEE80211_RADIOTAP_VHT_MCS_SHIFT 4 #define IEEE80211_RADIOTAP_CODING_LDPC_USERn 0x01 #define IEEE80211_CHAN_FHSS \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK) #define IEEE80211_CHAN_A \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_B \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK) #define IEEE80211_CHAN_PUREG \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_G \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN) #define IS_CHAN_FHSS(flags) \ ((flags & IEEE80211_CHAN_FHSS) == IEEE80211_CHAN_FHSS) #define IS_CHAN_A(flags) \ ((flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A) #define IS_CHAN_B(flags) \ ((flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B) #define IS_CHAN_PUREG(flags) \ ((flags & IEEE80211_CHAN_PUREG) == IEEE80211_CHAN_PUREG) #define IS_CHAN_G(flags) \ ((flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G) #define IS_CHAN_ANYG(flags) \ (IS_CHAN_PUREG(flags) || IS_CHAN_G(flags)) static void print_chaninfo(netdissect_options *ndo, uint16_t freq, int flags, int presentflags) { ND_PRINT((ndo, "%u MHz", freq)); if (presentflags & (1 << IEEE80211_RADIOTAP_MCS)) { /* * We have the MCS field, so this is 11n, regardless * of what the channel flags say. */ ND_PRINT((ndo, " 11n")); } else { if (IS_CHAN_FHSS(flags)) ND_PRINT((ndo, " FHSS")); if (IS_CHAN_A(flags)) { if (flags & IEEE80211_CHAN_HALF) ND_PRINT((ndo, " 11a/10Mhz")); else if (flags & IEEE80211_CHAN_QUARTER) ND_PRINT((ndo, " 11a/5Mhz")); else ND_PRINT((ndo, " 11a")); } if (IS_CHAN_ANYG(flags)) { if (flags & IEEE80211_CHAN_HALF) ND_PRINT((ndo, " 11g/10Mhz")); else if (flags & IEEE80211_CHAN_QUARTER) ND_PRINT((ndo, " 11g/5Mhz")); else ND_PRINT((ndo, " 11g")); } else if (IS_CHAN_B(flags)) ND_PRINT((ndo, " 11b")); if (flags & IEEE80211_CHAN_TURBO) ND_PRINT((ndo, " Turbo")); } /* * These apply to 11n. */ if (flags & IEEE80211_CHAN_HT20) ND_PRINT((ndo, " ht/20")); else if (flags & IEEE80211_CHAN_HT40D) ND_PRINT((ndo, " ht/40-")); else if (flags & IEEE80211_CHAN_HT40U) ND_PRINT((ndo, " ht/40+")); ND_PRINT((ndo, " ")); } static int print_radiotap_field(netdissect_options *ndo, struct cpack_state *s, uint32_t bit, uint8_t *flagsp, uint32_t presentflags) { u_int i; int rc; switch (bit) { case IEEE80211_RADIOTAP_TSFT: { uint64_t tsft; rc = cpack_uint64(s, &tsft); if (rc != 0) goto trunc; ND_PRINT((ndo, "%" PRIu64 "us tsft ", tsft)); break; } case IEEE80211_RADIOTAP_FLAGS: { uint8_t flagsval; rc = cpack_uint8(s, &flagsval); if (rc != 0) goto trunc; *flagsp = flagsval; if (flagsval & IEEE80211_RADIOTAP_F_CFP) ND_PRINT((ndo, "cfp ")); if (flagsval & IEEE80211_RADIOTAP_F_SHORTPRE) ND_PRINT((ndo, "short preamble ")); if (flagsval & IEEE80211_RADIOTAP_F_WEP) ND_PRINT((ndo, "wep ")); if (flagsval & IEEE80211_RADIOTAP_F_FRAG) ND_PRINT((ndo, "fragmented ")); if (flagsval & IEEE80211_RADIOTAP_F_BADFCS) ND_PRINT((ndo, "bad-fcs ")); break; } case IEEE80211_RADIOTAP_RATE: { uint8_t rate; rc = cpack_uint8(s, &rate); if (rc != 0) goto trunc; /* * XXX On FreeBSD rate & 0x80 means we have an MCS. On * Linux and AirPcap it does not. (What about * Mac OS X, NetBSD, OpenBSD, and DragonFly BSD?) * * This is an issue either for proprietary extensions * to 11a or 11g, which do exist, or for 11n * implementations that stuff a rate value into * this field, which also appear to exist. * * We currently handle that by assuming that * if the 0x80 bit is set *and* the remaining * bits have a value between 0 and 15 it's * an MCS value, otherwise it's a rate. If * there are cases where systems that use * "0x80 + MCS index" for MCS indices > 15, * or stuff a rate value here between 64 and * 71.5 Mb/s in here, we'll need a preference * setting. Such rates do exist, e.g. 11n * MCS 7 at 20 MHz with a long guard interval. */ if (rate >= 0x80 && rate <= 0x8f) { /* * XXX - we don't know the channel width * or guard interval length, so we can't * convert this to a data rate. * * If you want us to show a data rate, * use the MCS field, not the Rate field; * the MCS field includes not only the * MCS index, it also includes bandwidth * and guard interval information. * * XXX - can we get the channel width * from XChannel and the guard interval * information from Flags, at least on * FreeBSD? */ ND_PRINT((ndo, "MCS %u ", rate & 0x7f)); } else ND_PRINT((ndo, "%2.1f Mb/s ", .5 * rate)); break; } case IEEE80211_RADIOTAP_CHANNEL: { uint16_t frequency; uint16_t flags; rc = cpack_uint16(s, &frequency); if (rc != 0) goto trunc; rc = cpack_uint16(s, &flags); if (rc != 0) goto trunc; /* * If CHANNEL and XCHANNEL are both present, skip * CHANNEL. */ if (presentflags & (1 << IEEE80211_RADIOTAP_XCHANNEL)) break; print_chaninfo(ndo, frequency, flags, presentflags); break; } case IEEE80211_RADIOTAP_FHSS: { uint8_t hopset; uint8_t hoppat; rc = cpack_uint8(s, &hopset); if (rc != 0) goto trunc; rc = cpack_uint8(s, &hoppat); if (rc != 0) goto trunc; ND_PRINT((ndo, "fhset %d fhpat %d ", hopset, hoppat)); break; } case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: { int8_t dbm_antsignal; rc = cpack_int8(s, &dbm_antsignal); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm signal ", dbm_antsignal)); break; } case IEEE80211_RADIOTAP_DBM_ANTNOISE: { int8_t dbm_antnoise; rc = cpack_int8(s, &dbm_antnoise); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm noise ", dbm_antnoise)); break; } case IEEE80211_RADIOTAP_LOCK_QUALITY: { uint16_t lock_quality; rc = cpack_uint16(s, &lock_quality); if (rc != 0) goto trunc; ND_PRINT((ndo, "%u sq ", lock_quality)); break; } case IEEE80211_RADIOTAP_TX_ATTENUATION: { uint16_t tx_attenuation; rc = cpack_uint16(s, &tx_attenuation); if (rc != 0) goto trunc; ND_PRINT((ndo, "%d tx power ", -(int)tx_attenuation)); break; } case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: { uint8_t db_tx_attenuation; rc = cpack_uint8(s, &db_tx_attenuation); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB tx attenuation ", -(int)db_tx_attenuation)); break; } case IEEE80211_RADIOTAP_DBM_TX_POWER: { int8_t dbm_tx_power; rc = cpack_int8(s, &dbm_tx_power); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm tx power ", dbm_tx_power)); break; } case IEEE80211_RADIOTAP_ANTENNA: { uint8_t antenna; rc = cpack_uint8(s, &antenna); if (rc != 0) goto trunc; ND_PRINT((ndo, "antenna %u ", antenna)); break; } case IEEE80211_RADIOTAP_DB_ANTSIGNAL: { uint8_t db_antsignal; rc = cpack_uint8(s, &db_antsignal); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB signal ", db_antsignal)); break; } case IEEE80211_RADIOTAP_DB_ANTNOISE: { uint8_t db_antnoise; rc = cpack_uint8(s, &db_antnoise); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB noise ", db_antnoise)); break; } case IEEE80211_RADIOTAP_RX_FLAGS: { uint16_t rx_flags; rc = cpack_uint16(s, &rx_flags); if (rc != 0) goto trunc; /* Do nothing for now */ break; } case IEEE80211_RADIOTAP_XCHANNEL: { uint32_t flags; uint16_t frequency; uint8_t channel; uint8_t maxpower; rc = cpack_uint32(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint16(s, &frequency); if (rc != 0) goto trunc; rc = cpack_uint8(s, &channel); if (rc != 0) goto trunc; rc = cpack_uint8(s, &maxpower); if (rc != 0) goto trunc; print_chaninfo(ndo, frequency, flags, presentflags); break; } case IEEE80211_RADIOTAP_MCS: { uint8_t known; uint8_t flags; uint8_t mcs_index; static const char *ht_bandwidth[4] = { "20 MHz", "40 MHz", "20 MHz (L)", "20 MHz (U)" }; float htrate; rc = cpack_uint8(s, &known); if (rc != 0) goto trunc; rc = cpack_uint8(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &mcs_index); if (rc != 0) goto trunc; if (known & IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN) { /* * We know the MCS index. */ if (mcs_index <= MAX_MCS_INDEX) { /* * And it's in-range. */ if (known & (IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN|IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN)) { /* * And we know both the bandwidth and * the guard interval, so we can look * up the rate. */ htrate = ieee80211_float_htrates \ [mcs_index] \ [((flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK) == IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 ? 1 : 0)] \ [((flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? 1 : 0)]; } else { /* * We don't know both the bandwidth * and the guard interval, so we can * only report the MCS index. */ htrate = 0.0; } } else { /* * The MCS value is out of range. */ htrate = 0.0; } if (htrate != 0.0) { /* * We have the rate. * Print it. */ ND_PRINT((ndo, "%.1f Mb/s MCS %u ", htrate, mcs_index)); } else { /* * We at least have the MCS index. * Print it. */ ND_PRINT((ndo, "MCS %u ", mcs_index)); } } if (known & IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN) { ND_PRINT((ndo, "%s ", ht_bandwidth[flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK])); } if (known & IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN) { ND_PRINT((ndo, "%s GI ", (flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? "short" : "long")); } if (known & IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN) { ND_PRINT((ndo, "%s ", (flags & IEEE80211_RADIOTAP_MCS_HT_GREENFIELD) ? "greenfield" : "mixed")); } if (known & IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN) { ND_PRINT((ndo, "%s FEC ", (flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC) ? "LDPC" : "BCC")); } if (known & IEEE80211_RADIOTAP_MCS_STBC_KNOWN) { ND_PRINT((ndo, "RX-STBC%u ", (flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >> IEEE80211_RADIOTAP_MCS_STBC_SHIFT)); } break; } case IEEE80211_RADIOTAP_AMPDU_STATUS: { uint32_t reference_num; uint16_t flags; uint8_t delim_crc; uint8_t reserved; rc = cpack_uint32(s, &reference_num); if (rc != 0) goto trunc; rc = cpack_uint16(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &delim_crc); if (rc != 0) goto trunc; rc = cpack_uint8(s, &reserved); if (rc != 0) goto trunc; /* Do nothing for now */ break; } case IEEE80211_RADIOTAP_VHT: { uint16_t known; uint8_t flags; uint8_t bandwidth; uint8_t mcs_nss[4]; uint8_t coding; uint8_t group_id; uint16_t partial_aid; static const char *vht_bandwidth[32] = { "20 MHz", "40 MHz", "20 MHz (L)", "20 MHz (U)", "80 MHz", "80 MHz (L)", "80 MHz (U)", "80 MHz (LL)", "80 MHz (LU)", "80 MHz (UL)", "80 MHz (UU)", "160 MHz", "160 MHz (L)", "160 MHz (U)", "160 MHz (LL)", "160 MHz (LU)", "160 MHz (UL)", "160 MHz (UU)", "160 MHz (LLL)", "160 MHz (LLU)", "160 MHz (LUL)", "160 MHz (UUU)", "160 MHz (ULL)", "160 MHz (ULU)", "160 MHz (UUL)", "160 MHz (UUU)", "unknown (26)", "unknown (27)", "unknown (28)", "unknown (29)", "unknown (30)", "unknown (31)" }; rc = cpack_uint16(s, &known); if (rc != 0) goto trunc; rc = cpack_uint8(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &bandwidth); if (rc != 0) goto trunc; for (i = 0; i < 4; i++) { rc = cpack_uint8(s, &mcs_nss[i]); if (rc != 0) goto trunc; } rc = cpack_uint8(s, &coding); if (rc != 0) goto trunc; rc = cpack_uint8(s, &group_id); if (rc != 0) goto trunc; rc = cpack_uint16(s, &partial_aid); if (rc != 0) goto trunc; for (i = 0; i < 4; i++) { u_int nss, mcs; nss = mcs_nss[i] & IEEE80211_RADIOTAP_VHT_NSS_MASK; mcs = (mcs_nss[i] & IEEE80211_RADIOTAP_VHT_MCS_MASK) >> IEEE80211_RADIOTAP_VHT_MCS_SHIFT; if (nss == 0) continue; ND_PRINT((ndo, "User %u MCS %u ", i, mcs)); ND_PRINT((ndo, "%s FEC ", (coding & (IEEE80211_RADIOTAP_CODING_LDPC_USERn << i)) ? "LDPC" : "BCC")); } if (known & IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN) { ND_PRINT((ndo, "%s ", vht_bandwidth[bandwidth & IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK])); } if (known & IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN) { ND_PRINT((ndo, "%s GI ", (flags & IEEE80211_RADIOTAP_VHT_SHORT_GI) ? "short" : "long")); } break; } default: /* this bit indicates a field whose * size we do not know, so we cannot * proceed. Just print the bit number. */ ND_PRINT((ndo, "[bit %u] ", bit)); return -1; } return 0; trunc: ND_PRINT((ndo, "%s", tstr)); return rc; } static int print_in_radiotap_namespace(netdissect_options *ndo, struct cpack_state *s, uint8_t *flags, uint32_t presentflags, int bit0) { #define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x))) #define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x))) #define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x))) #define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x))) #define BITNO_2(x) (((x) & 2) ? 1 : 0) uint32_t present, next_present; int bitno; enum ieee80211_radiotap_type bit; int rc; for (present = presentflags; present; present = next_present) { /* * Clear the least significant bit that is set. */ next_present = present & (present - 1); /* * Get the bit number, within this presence word, * of the remaining least significant bit that * is set. */ bitno = BITNO_32(present ^ next_present); /* * Stop if this is one of the "same meaning * in all presence flags" bits. */ if (bitno >= IEEE80211_RADIOTAP_NAMESPACE) break; /* * Get the radiotap bit number of that bit. */ bit = (enum ieee80211_radiotap_type)(bit0 + bitno); rc = print_radiotap_field(ndo, s, bit, flags, presentflags); if (rc != 0) return rc; } return 0; } static u_int ieee802_11_radio_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen) { #define BIT(n) (1U << n) #define IS_EXTENDED(__p) \ (EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0 struct cpack_state cpacker; const struct ieee80211_radiotap_header *hdr; uint32_t presentflags; const uint32_t *presentp, *last_presentp; int vendor_namespace; uint8_t vendor_oui[3]; uint8_t vendor_subnamespace; uint16_t skip_length; int bit0; u_int len; uint8_t flags; int pad; u_int fcslen; if (caplen < sizeof(*hdr)) { ND_PRINT((ndo, "%s", tstr)); return caplen; } hdr = (const struct ieee80211_radiotap_header *)p; len = EXTRACT_LE_16BITS(&hdr->it_len); /* * If we don't have the entire radiotap header, just give up. */ if (caplen < len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } cpack_init(&cpacker, (const uint8_t *)hdr, len); /* align against header start */ cpack_advance(&cpacker, sizeof(*hdr)); /* includes the 1st bitmap */ for (last_presentp = &hdr->it_present; (const u_char*)(last_presentp + 1) <= p + len && IS_EXTENDED(last_presentp); last_presentp++) cpack_advance(&cpacker, sizeof(hdr->it_present)); /* more bitmaps */ /* are there more bitmap extensions than bytes in header? */ if ((const u_char*)(last_presentp + 1) > p + len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } /* * Start out at the beginning of the default radiotap namespace. */ bit0 = 0; vendor_namespace = 0; memset(vendor_oui, 0, 3); vendor_subnamespace = 0; skip_length = 0; /* Assume no flags */ flags = 0; /* Assume no Atheros padding between 802.11 header and body */ pad = 0; /* Assume no FCS at end of frame */ fcslen = 0; for (presentp = &hdr->it_present; presentp <= last_presentp; presentp++) { presentflags = EXTRACT_LE_32BITS(presentp); /* * If this is a vendor namespace, we don't handle it. */ if (vendor_namespace) { /* * Skip past the stuff we don't understand. * If we add support for any vendor namespaces, * it'd be added here; use vendor_oui and * vendor_subnamespace to interpret the fields. */ if (cpack_advance(&cpacker, skip_length) != 0) { /* * Ran out of space in the packet. */ break; } /* * We've skipped it all; nothing more to * skip. */ skip_length = 0; } else { if (print_in_radiotap_namespace(ndo, &cpacker, &flags, presentflags, bit0) != 0) { /* * Fatal error - can't process anything * more in the radiotap header. */ break; } } /* * Handle the namespace switch bits; we've already handled * the extension bit in all but the last word above. */ switch (presentflags & (BIT(IEEE80211_RADIOTAP_NAMESPACE)|BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE))) { case 0: /* * We're not changing namespaces. * advance to the next 32 bits in the current * namespace. */ bit0 += 32; break; case BIT(IEEE80211_RADIOTAP_NAMESPACE): /* * We're switching to the radiotap namespace. * Reset the presence-bitmap index to 0, and * reset the namespace to the default radiotap * namespace. */ bit0 = 0; vendor_namespace = 0; memset(vendor_oui, 0, 3); vendor_subnamespace = 0; skip_length = 0; break; case BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE): /* * We're switching to a vendor namespace. * Reset the presence-bitmap index to 0, * note that we're in a vendor namespace, * and fetch the fields of the Vendor Namespace * item. */ bit0 = 0; vendor_namespace = 1; if ((cpack_align_and_reserve(&cpacker, 2)) == NULL) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[0]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[1]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[2]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_subnamespace) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint16(&cpacker, &skip_length) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } break; default: /* * Illegal combination. The behavior in this * case is undefined by the radiotap spec; we * just ignore both bits. */ break; } } if (flags & IEEE80211_RADIOTAP_F_DATAPAD) pad = 1; /* Atheros padding */ if (flags & IEEE80211_RADIOTAP_F_FCS) fcslen = 4; /* FCS at end of packet */ return len + ieee802_11_print(ndo, p + len, length - len, caplen - len, pad, fcslen); #undef BITNO_32 #undef BITNO_16 #undef BITNO_8 #undef BITNO_4 #undef BITNO_2 #undef BIT } static u_int ieee802_11_avs_radio_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen) { uint32_t caphdr_len; if (caplen < 8) { ND_PRINT((ndo, "%s", tstr)); return caplen; } caphdr_len = EXTRACT_32BITS(p + 4); if (caphdr_len < 8) { /* * Yow! The capture header length is claimed not * to be large enough to include even the version * cookie or capture header length! */ ND_PRINT((ndo, "%s", tstr)); return caplen; } if (caplen < caphdr_len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } return caphdr_len + ieee802_11_print(ndo, p + caphdr_len, length - caphdr_len, caplen - caphdr_len, 0, 0); } #define PRISM_HDR_LEN 144 #define WLANCAP_MAGIC_COOKIE_BASE 0x80211000 #define WLANCAP_MAGIC_COOKIE_V1 0x80211001 #define WLANCAP_MAGIC_COOKIE_V2 0x80211002 /* * For DLT_PRISM_HEADER; like DLT_IEEE802_11, but with an extra header, * containing information such as radio information, which we * currently ignore. * * If, however, the packet begins with WLANCAP_MAGIC_COOKIE_V1 or * WLANCAP_MAGIC_COOKIE_V2, it's really DLT_IEEE802_11_RADIO_AVS * (currently, on Linux, there's no ARPHRD_ type for * DLT_IEEE802_11_RADIO_AVS, as there is a ARPHRD_IEEE80211_PRISM * for DLT_PRISM_HEADER, so ARPHRD_IEEE80211_PRISM is used for * the AVS header, and the first 4 bytes of the header are used to * indicate whether it's a Prism header or an AVS header). */ u_int prism_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t msgcode; if (caplen < 4) { ND_PRINT((ndo, "%s", tstr)); return caplen; } msgcode = EXTRACT_32BITS(p); if (msgcode == WLANCAP_MAGIC_COOKIE_V1 || msgcode == WLANCAP_MAGIC_COOKIE_V2) return ieee802_11_avs_radio_print(ndo, p, length, caplen); if (caplen < PRISM_HDR_LEN) { ND_PRINT((ndo, "%s", tstr)); return caplen; } return PRISM_HDR_LEN + ieee802_11_print(ndo, p + PRISM_HDR_LEN, length - PRISM_HDR_LEN, caplen - PRISM_HDR_LEN, 0, 0); } /* * For DLT_IEEE802_11_RADIO; like DLT_IEEE802_11, but with an extra * header, containing information such as radio information. */ u_int ieee802_11_radio_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_radio_print(ndo, p, h->len, h->caplen); } /* * For DLT_IEEE802_11_RADIO_AVS; like DLT_IEEE802_11, but with an * extra header, containing information such as radio information, * which we currently ignore. */ u_int ieee802_11_radio_avs_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_avs_radio_print(ndo, p, h->len, h->caplen); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2683_0
crossvul-cpp_data_bad_1018_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII FFFFF FFFFF % % T I F F % % T I FFF FFF % % T I F F % % T IIIII F F % % % % % % Read/Write TIFF 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. */ #ifdef __VMS #define JPEG_SUPPORT 1 #endif #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.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/constitute.h" #include "magick/draw.h" #include "magick/enhance.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/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread_.h" #include "magick/token.h" #include "magick/utility.h" #if defined(MAGICKCORE_TIFF_DELEGATE) # if defined(MAGICKCORE_HAVE_TIFFCONF_H) # include <tiffconf.h> # endif # include <tiff.h> # include <tiffio.h> # if !defined(COMPRESSION_ADOBE_DEFLATE) # define COMPRESSION_ADOBE_DEFLATE 8 # endif # if !defined(PREDICTOR_HORIZONTAL) # define PREDICTOR_HORIZONTAL 2 # endif # if !defined(TIFFTAG_COPYRIGHT) # define TIFFTAG_COPYRIGHT 33432 # endif # if !defined(TIFFTAG_OPIIMAGEID) # define TIFFTAG_OPIIMAGEID 32781 # endif # if defined(COMPRESSION_ZSTD) && defined(MAGICKCORE_ZSTD_DELEGATE) # include <zstd.h> # endif #include "psd-private.h" /* Typedef declarations. */ typedef enum { ReadSingleSampleMethod, ReadRGBAMethod, ReadCMYKAMethod, ReadYCCKMethod, ReadStripMethod, ReadTileMethod, ReadGenericMethod } TIFFMethodType; #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) typedef struct _ExifInfo { unsigned int tag, type, variable_length; const char *property; } ExifInfo; static const ExifInfo exif_info[] = { { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" }, { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" }, { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" }, { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" }, { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" }, { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" }, { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" }, { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" }, { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" }, { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" }, { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" }, { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" }, { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" }, { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" }, { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" }, { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" }, { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" }, { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" }, { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" }, { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" }, { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" }, { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" }, { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" }, { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" }, { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" }, { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" }, { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" }, { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" }, { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" }, { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" }, { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" }, { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" }, { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" }, { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" }, { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" }, { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" }, { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" }, { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" }, { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" }, { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" }, { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" }, { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" }, { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" }, { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" }, { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" }, { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" }, { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" }, { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" }, { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" }, { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" }, { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" }, { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" }, { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" }, { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" }, { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" }, { 0, 0, 0, (char *) NULL } }; #endif /* Global declarations. */ static MagickThreadKey tiff_exception; static SemaphoreInfo *tiff_semaphore = (SemaphoreInfo *) NULL; static TIFFErrorHandler error_handler, warning_handler; static volatile MagickBooleanType instantiate_key = MagickFalse; /* Forward declarations. */ static Image * ReadTIFFImage(const ImageInfo *,ExceptionInfo *); static MagickBooleanType WriteGROUP4Image(const ImageInfo *,Image *), WritePTIFImage(const ImageInfo *,Image *), WriteTIFFImage(const ImageInfo *,Image *); static void InitPSDInfo(Image *image,Image *layer,PSDInfo *info) { info->version=1; info->columns=layer->columns; info->rows=layer->rows; info->mode=10; /* Set mode to a value that won't change the colorspace */ /* Assume that image has matte */ if (IsGrayImage(image,&image->exception) != MagickFalse) info->channels=2U; else if (image->storage_class == PseudoClass) { info->mode=2; info->channels=2U; } else { if (image->colorspace != CMYKColorspace) info->channels=4U; else info->channels=5U; } if (image->matte == MagickFalse) info->channels--; info->min_channels=info->channels; if (image->matte != MagickFalse) info->min_channels--; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTIFF() returns MagickTrue if the image format type, identified by the % magick string, is TIFF. % % The format of the IsTIFF method is: % % MagickBooleanType IsTIFF(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 IsTIFF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\115\115\000\052",4) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\052\000",4) == 0) return(MagickTrue); #if defined(TIFF_VERSION_BIG) if (length < 8) return(MagickFalse); if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0) return(MagickTrue); if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0) return(MagickTrue); #endif return(MagickFalse); } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGROUP4Image() reads a raw CCITT Group 4 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 ReadGROUP4Image method is: % % Image *ReadGROUP4Image(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 inline size_t WriteLSBLong(FILE *file,const unsigned int value) { unsigned char buffer[4]; buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); return(fwrite(buffer,1,4,file)); } static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* 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); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); if (length != 10) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(unsigned int) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(unsigned int) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(unsigned int) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(unsigned int) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(unsigned int) image->x_resolution); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); if (ferror(file) != 0) { (void) fclose(file); ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); } (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MaxTextExtent); (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIFFImage() reads a Tagged 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 ReadTIFFImage method is: % % Image *ReadTIFFImage(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 inline unsigned char ClampYCC(double value) { value=255.0-value; if (value < 0.0) return((unsigned char)0); if (value > 255.0) return((unsigned char)255); return((unsigned char)(value)); } static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(q)+0.5; if (b > 1.0) b-=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; break; } } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length) { MagickBooleanType status; StringInfo *profile; if (length < 4) return(MagickFalse); profile=BlobToStringInfo(datum,(size_t) length); if (profile == (StringInfo *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=SetImageProfile(image,name,profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); return(MagickTrue); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int TIFFCloseBlob(thandle_t image) { (void) CloseBlob((Image *) image); return(0); } static void TIFFErrors(const char *,const char *,va_list) magick_attribute((__format__ (__printf__,2,0))); static void TIFFErrors(const char *module,const char *format,va_list error) { char message[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent-2,format,error); #else (void) vsprintf(message,format,error); #endif message[MaxTextExtent-2]='\0'; (void) ConcatenateMagickString(message,".",MaxTextExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message, "`%s'",module); } static toff_t TIFFGetBlobSize(thandle_t image) { return((toff_t) GetBlobSize((Image *) image)); } static void TIFFGetProfiles(TIFF *tiff,Image *image) { uint32 length; unsigned char *profile; length=0; #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length); #endif #if defined(TIFFTAG_PHOTOSHOP) if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"8bim",profile,(ssize_t) length); #endif #if defined(TIFFTAG_RICHTIFFIPTC) if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) { if (TIFFIsByteSwapped(tiff) != 0) TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length); (void) ReadProfile(image,"iptc",profile,4L*length); } #endif #if defined(TIFFTAG_XMLPACKET) if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"xmp",profile,(ssize_t) length); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length); if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length); } static void TIFFGetProperties(TIFF *tiff,Image *image) { char message[MaxTextExtent], *text; uint32 count, type; if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:artist",text); if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:copyright",text); if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:timestamp",text); if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:document",text); if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:hostcomputer",text); if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"comment",text); if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:make",text); if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:model",text); if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message); } if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"label",text); if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) && (text != (char *) NULL)) (void) SetImageProperty(image,"tiff:software",text); if ((TIFFGetField(tiff,33423,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message); } if ((TIFFGetField(tiff,36867,&count,&text) == 1) && (text != (char *) NULL)) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE"); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE"); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK"); break; } default: break; } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans[2] = { NULL, NULL }; /* Read EXIF properties. */ offset=0; if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1) return; directory=TIFFCurrentDirectory(tiff); if (TIFFReadEXIFDirectory(tiff,offset) != 1) { TIFFSetDirectory(tiff,directory); return; } for (i=0; exif_info[i].tag != 0; i++) { *value='\0'; switch (exif_info[i].type) { case TIFF_ASCII: { char *ascii; ascii=(char *) NULL; if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) ((MagickOffsetType) long8y)); break; } #endif case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: { float floaty; floaty=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&floaty,sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } TIFFSetDirectory(tiff,directory); #else (void) tiff; (void) image; #endif } static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size) { *base=(tdata_t *) GetBlobStreamData((Image *) image); if (*base != (tdata_t *) NULL) *size=(toff_t) GetBlobSize((Image *) image); if (*base != (tdata_t *) NULL) return(1); return(0); } static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) ReadBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static int32 TIFFReadPixels(TIFF *tiff,const tsample_t sample,const ssize_t row, tdata_t scanline) { int32 status; status=TIFFReadScanline(tiff,scanline,(uint32) row,sample); return(status); } static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence) { return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence)); } static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size) { (void) image; (void) base; (void) size; } static void TIFFWarnings(const char *,const char *,va_list) magick_attribute((__format__ (__printf__,2,0))); static void TIFFWarnings(const char *module,const char *format,va_list warning) { char message[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif message[MaxTextExtent-2]='\0'; (void) ConcatenateMagickString(message,".",MaxTextExtent); exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception); if (exception != (ExceptionInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'",module); } static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size) { tsize_t count; count=(tsize_t) WriteBlob((Image *) image,(size_t) size, (unsigned char *) data); return(count); } static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric, uint16 bits_per_sample,uint16 samples_per_pixel) { #define BUFFER_SIZE 2048 MagickOffsetType position, offset; register size_t i; TIFFMethodType method; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif *value; unsigned char buffer[BUFFER_SIZE+32]; unsigned short length; /* Only support 8 bit for now. */ if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) || (samples_per_pixel != 4)) return(ReadGenericMethod); /* Search for Adobe APP14 JPEG marker. */ value=NULL; if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value) || (value == NULL)) return(ReadRGBAMethod); position=TellBlob(image); offset=(MagickOffsetType) (value[0]); if (SeekBlob(image,offset,SEEK_SET) != offset) return(ReadRGBAMethod); method=ReadRGBAMethod; if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE) { for (i=0; i < BUFFER_SIZE; i++) { while (i < BUFFER_SIZE) { if (buffer[i++] == 255) break; } while (i < BUFFER_SIZE) { if (buffer[++i] != 255) break; } if (buffer[i++] == 216) /* JPEG_MARKER_SOI */ continue; length=(unsigned short) (((unsigned int) (buffer[i] << 8) | (unsigned int) buffer[i+1]) & 0xffff); if (i+(size_t) length >= BUFFER_SIZE) break; if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */ { if (length != 14) break; /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */ if (buffer[i+13] == 2) method=ReadYCCKMethod; break; } i+=(size_t) length; } } (void) SeekBlob(image,position,SEEK_SET); return(method); } static void TIFFReadPhotoshopLayers(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *option; const StringInfo *profile; Image *layers; ImageInfo *clone_info; PSDInfo info; register ssize_t i; if (GetImageListLength(image) != 1) return; if ((image_info->number_scenes == 1) && (image_info->scene == 0)) return; option=GetImageOption(image_info,"tiff:ignore-layers"); if (option != (const char * ) NULL) return; profile=GetImageProfile(image,"tiff:37724"); if (profile == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) profile->length-8; i++) { if (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (profile->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (profile->length-8)) return; layers=CloneImage(image,0,0,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,profile->datum,profile->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); InitPSDInfo(image, layers, &info); clone_info=CloneImageInfo(image_info); clone_info->number_scenes=0; (void) ReadPSDLayers(layers,clone_info,&info,MagickFalse,exception); clone_info=DestroyImageInfo(clone_info); /* we need to set the datum in case a realloc happend */ ((StringInfo *) profile)->datum=GetBlobStreamData(layers); InheritException(exception,&layers->exception); DeleteImageFromList(&layers); if (layers != (Image *) NULL) { SetImageArtifact(image,"tiff:has-layers","true"); AppendImageToList(&image,layers); while (layers != (Image *) NULL) { SetImageArtifact(layers,"tiff:has-layers","true"); DetachBlob(layers->blob); layers=GetNextImageInList(layers); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowTIFFException(severity,message) \ { \ if (tiff_pixels != (unsigned char *) NULL) \ tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \ if (quantum_info != (QuantumInfo *) NULL) \ quantum_info=DestroyQuantumInfo(quantum_info); \ TIFFClose(tiff); \ ThrowReaderException(severity,message); \ } const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType more_frames, status; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t number_pixels, pad; ssize_t y; TIFF *tiff; TIFFMethodType method; uint16 compress_tag, bits_per_sample, endian, extra_samples, interlace, max_sample_value, min_sample_value, orientation, pages, photometric, *sample_info, sample_format, samples_per_pixel, units, value; uint32 height, rows_per_strip, width; unsigned char *tiff_pixels; /* Open image. */ 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); } (void) SetMagickThreadValue(tiff_exception,exception); tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } if (exception->severity > ErrorException) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } if (image_info->number_scenes != 0) { /* Generate blank images for subimage specification (e.g. image.tif[4]. We need to check the number of directores because it is possible that the subimage(s) are stored in the photoshop profile. */ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) { for (i=0; i < (ssize_t) image_info->scene; i++) { status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status == MagickFalse) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } more_frames=MagickTrue; do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning photometric=PHOTOMETRIC_RGB; if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample == 64)) && ((bits_per_sample <= 0) || (bits_per_sample > 32))) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); break; } } if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", (unsigned int) width,(unsigned int) height); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", interlace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Bits per sample: %u",bits_per_sample); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Min sample value: %u",min_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Max sample value: %u",max_sample_value); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " "interpretation: %s",GetImageProperty(image,"tiff:photometric")); } image->columns=(size_t) width; image->rows=(size_t) height; image->depth=(size_t) bits_per_sample; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", (double) image->depth); image->endian=MSBEndian; if (endian == FILLORDER_LSB2MSB) image->endian=LSBEndian; #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) if (TIFFIsBigEndian(tiff) == 0) { (void) SetImageProperty(image,"tiff:endian","lsb"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=y_resolution; } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1) { if (units == RESUNIT_INCH) image->units=PixelsPerInchResolution; if (units == RESUNIT_CENTIMETER) image->units=PixelsPerCentimeterResolution; } if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1)) { image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5); } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1) image->orientation=(OrientationType) orientation; if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.white_point.x=chromaticity[0]; image->chromaticity.white_point.y=chromaticity[1]; } } if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1) { if (chromaticity != (float *) NULL) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { TIFFClose(tiff); ThrowReaderException(CoderError,"CompressNotSupported"); } #endif switch (compress_tag) { case COMPRESSION_NONE: image->compression=NoCompression; break; case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break; case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break; case COMPRESSION_JPEG: { image->compression=JPEGCompression; #if defined(JPEG_SUPPORT) { char sampling_factor[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal, &vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling Factors: %s",sampling_factor); } } #endif break; } case COMPRESSION_OJPEG: image->compression=JPEGCompression; break; #if defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: image->compression=LZMACompression; break; #endif case COMPRESSION_LZW: image->compression=LZWCompression; break; case COMPRESSION_DEFLATE: image->compression=ZipCompression; break; case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break; #if defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: image->compression=WebPCompression; break; #endif #if defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: image->compression=ZstdCompression; break; #endif default: image->compression=RLECompression; break; } tiff_pixels=(unsigned char *) NULL; quantum_info=(QuantumInfo *) NULL; if ((photometric == PHOTOMETRIC_PALETTE) && (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize)) { size_t colors; colors=(size_t) GetQuantumRange(bits_per_sample)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; size_t range; uint16 *blue_colormap, *green_colormap, *red_colormap; /* Initialize colormap. */ tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap, &green_colormap,&blue_colormap); if (tiff_status == 1) { if ((red_colormap != (uint16 *) NULL) && (green_colormap != (uint16 *) NULL) && (blue_colormap != (uint16 *) NULL)) { range=255; /* might be old style 8-bit colormap */ for (i=0; i < (ssize_t) image->colors; i++) if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) || (blue_colormap[i] >= 256)) { range=65535; break; } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ClampToQuantum(((double) QuantumRange*red_colormap[i])/range); image->colormap[i].green=ClampToQuantum(((double) QuantumRange*green_colormap[i])/range); image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*blue_colormap[i])/range); } } } } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) { TIFFClose(tiff); InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (sample_format == SAMPLEFORMAT_UINT) status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat); if (sample_format == SAMPLEFORMAT_INT) status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat); if (sample_format == SAMPLEFORMAT_IEEEFP) status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; switch (photometric) { case PHOTOMETRIC_MINISBLACK: { quantum_info->min_is_white=MagickFalse; break; } case PHOTOMETRIC_MINISWHITE: { quantum_info->min_is_white=MagickTrue; break; } default: break; } tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples, &sample_info); if (tiff_status == 1) { (void) SetImageProperty(image,"tiff:alpha","unspecified"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } } if (image->matte != MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); method=ReadGenericMethod; rows_per_strip=(uint32) image->rows; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if (rows_per_strip > (uint32) image->rows) rows_per_strip=(uint32) image->rows; if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG)) if ((image->matte == MagickFalse) || (samples_per_pixel >= 4)) method=ReadRGBAMethod; if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE)) if ((image->matte == MagickFalse) || (samples_per_pixel >= 5)) method=ReadCMYKAMethod; if ((photometric != PHOTOMETRIC_RGB) && (photometric != PHOTOMETRIC_CIELAB) && (photometric != PHOTOMETRIC_SEPARATED)) method=ReadGenericMethod; if (image->storage_class == PseudoClass) method=ReadSingleSampleMethod; if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) method=ReadSingleSampleMethod; if ((photometric != PHOTOMETRIC_SEPARATED) && (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64)) method=ReadGenericMethod; if (image->compression == JPEGCompression) method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, samples_per_pixel); if (compress_tag == COMPRESSION_JBIG) method=ReadStripMethod; if (TIFFIsTiled(tiff) != MagickFalse) method=ReadTileMethod; quantum_info->endian=LSBEndian; quantum_type=RGBQuantum; if (TIFFScanlineSize(tiff) <= 0) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); if (((MagickSizeType) TIFFScanlineSize(tiff)) > (2*GetBlobSize(image))) ThrowTIFFException(CorruptImageError,"InsufficientImageDataInFile"); number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t) image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/ log(2.0))),image->columns*rows_per_strip)*sizeof(uint32)); tiff_pixels=(unsigned char *) AcquireMagickMemory(number_pixels); if (tiff_pixels == (unsigned char *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(tiff_pixels,0,number_pixels); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadRGBAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0); quantum_type=RGBQuantum; if (image->matte != MagickFalse) { quantum_type=RGBAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); } if (image->colorspace == CMYKColorspace) { pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0); quantum_type=CMYKQuantum; if (image->matte != MagickFalse) { quantum_type=CMYKAQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0); } } status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3)); if (status == MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadCMYKAMethod: { /* Convert TIFF image to DirectClass MIFF image. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,(tsample_t) i,y,(char *) tiff_pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (image->colorspace != CMYKColorspace) switch (i) { case 0: quantum_type=RedQuantum; break; case 1: quantum_type=GreenQuantum; break; case 2: quantum_type=BlueQuantum; break; case 3: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } else switch (i) { case 0: quantum_type=CyanQuantum; break; case 1: quantum_type=MagentaQuantum; break; case 2: quantum_type=YellowQuantum; break; case 3: quantum_type=BlackQuantum; break; case 4: quantum_type=AlphaQuantum; break; default: quantum_type=UndefinedQuantum; break; } (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,tiff_pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadYCCKMethod: { for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tiff_pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; p+=4; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadStripMethod: { register uint32 *p; /* Convert stripped TIFF image to DirectClass MIFF image. */ (void) SetImageStorageClass(image,DirectClass); i=0; p=(uint32 *) NULL; 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; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) tiff_pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte == MagickFalse) SetPixelOpacity(q,OpaqueOpacity); else SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case ReadTileMethod: { register uint32 *p; uint32 *tile_pixels, columns, rows; /* Convert tiled TIFF image to DirectClass MIFF image. */ if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) || (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1)) ThrowTIFFException(CoderError,"ImageIsNotTiled"); if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) || (AcquireMagickResource(HeightResource,rows) == MagickFalse)) ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit"); (void) SetImageStorageClass(image,DirectClass); if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows* sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; size_t columns_remaining, rows_remaining; rows_remaining=image->rows-y; if ((ssize_t) (y+rows) < (ssize_t) image->rows) rows_remaining=rows; tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining, exception); if (tile == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=columns) { size_t column, row; if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0) break; columns_remaining=image->columns-x; if ((ssize_t) (x+columns) < (ssize_t) image->columns) columns_remaining=columns; p=tile_pixels+(rows-rows_remaining)*columns; q=tile+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelOpacity(q,OpaqueOpacity); q++; p++; } p+=columns-columns_remaining; q-=(image->columns+columns_remaining); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels); break; } case ReadGenericMethod: default: { MemoryInfo *pixel_info; MagickSizeType number_pixels; register uint32 *p; uint32 *pixels; /* Convert TIFF image to DirectClass MIFF image. */ (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) image->columns*image->rows; if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info); (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32) image->rows,(uint32 *) pixels,0); /* Convert image to DirectClass pixel packets. */ p=pixels+number_pixels-1; 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; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte == MagickFalse) SetPixelOpacity(q,OpaqueOpacity); else SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixel_info=RelinquishVirtualMemory(pixel_info); break; } } tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); SetQuantumImageType(image,quantum_type); next_tiff_frame: if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (photometric == PHOTOMETRIC_CIELAB) DecodeLabImage(image,exception); if ((photometric == PHOTOMETRIC_LOGL) || (photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) { image->type=GrayscaleType; if (bits_per_sample == 1) image->type=BilevelType; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (more_frames != MagickFalse) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,image->scene-1, image->scene); if (status == MagickFalse) break; } } while ((status != MagickFalse) && (more_frames != MagickFalse)); TIFFClose(tiff); TIFFReadPhotoshopLayers(image_info,image,exception); if ((image_info->number_scenes != 0) && (image_info->scene >= GetImageListLength(image))) status=MagickFalse; if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIFFImage() adds properties for the TIFF 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 RegisterTIFFImage method is: % % size_t RegisterTIFFImage(void) % */ #if defined(MAGICKCORE_TIFF_DELEGATE) #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) static TIFFExtendProc tag_extender = (TIFFExtendProc) NULL; static void TIFFIgnoreTags(TIFF *tiff) { char *q; const char *p, *tags; Image *image; register ssize_t i; size_t count; TIFFFieldInfo *ignore; if (TIFFGetReadProc(tiff) != TIFFReadBlob) return; image=(Image *)TIFFClientdata(tiff); tags=GetImageArtifact(image,"tiff:ignore-tags"); if (tags == (const char *) NULL) return; count=0; p=tags; while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; (void) strtol(p,&q,10); if (p == q) return; p=q; count++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (count == 0) return; i=0; p=tags; ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore)); if (ignore == (TIFFFieldInfo *) NULL) return; /* This also sets field_bit to 0 (FIELD_IGNORE) */ memset(ignore,0,count*sizeof(*ignore)); while (*p != '\0') { while ((isspace((int) ((unsigned char) *p)) != 0)) p++; ignore[i].field_tag=(ttag_t) strtol(p,&q,10); p=q; i++; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count); ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore); } static void TIFFTagExtender(TIFF *tiff) { static const TIFFFieldInfo TIFFExtensions[] = { { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "PhotoshopLayerData" }, { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1, (char *) "Microscope" } }; TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/ sizeof(*TIFFExtensions)); if (tag_extender != (TIFFExtendProc) NULL) (*tag_extender)(tiff); TIFFIgnoreTags(tiff); } #endif #endif ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MaxTextExtent]; MagickInfo *entry; #if defined(MAGICKCORE_TIFF_DELEGATE) if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); #endif *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=SetMagickInfo("GROUP4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw CCITT Group4"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PTIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Pyramid encoded TIFF"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF64"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->adjoin=MagickFalse; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Tagged Image File Format (64-bit)"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIFFImage() removes format registrations made by the TIFF module % from the list of supported formats. % % The format of the UnregisterTIFFImage method is: % % UnregisterTIFFImage(void) % */ ModuleExport void UnregisterTIFFImage(void) { (void) UnregisterMagickInfo("TIFF64"); (void) UnregisterMagickInfo("TIFF"); (void) UnregisterMagickInfo("TIF"); (void) UnregisterMagickInfo("PTIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key != MagickFalse) { if (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); DestroySemaphoreInfo(&tiff_semaphore); #endif } #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G R O U P 4 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format. % % The format of the WriteGROUP4Image method is: % % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; FILE *file; Image *huffman_image; ImageInfo *write_info; int unique_file; MagickBooleanType status; register ssize_t i; ssize_t count; TIFF *tiff; toff_t *byte_count, strip_size; unsigned char *buffer; /* Write image as CCITT Group4 TIFF image to a temporary 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); huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (huffman_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } huffman_image->endian=MSBEndian; file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1); (void) SetImageType(image,BilevelType); write_info->compression=Group4Compression; write_info->type=BilevelType; status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } tiff=TIFFOpen(filename,"rb"); if (tiff == (TIFF *) NULL) { huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); return(MagickFalse); } /* Allocate raw strip buffer. */ if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); return(MagickFalse); } strip_size=byte_count[0]; for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) if (byte_count[i] > strip_size) strip_size=byte_count[i]; buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size, sizeof(*buffer)); if (buffer == (unsigned char *) NULL) { TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image_info->filename); } /* Compress runlength encoded to 2D Huffman pixels. */ for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++) { count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size); if (WriteBlob(image,(size_t) count,buffer) != count) status=MagickFalse; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); TIFFClose(tiff); huffman_image=DestroyImage(huffman_image); (void) fclose(file); (void) RelinquishUniqueFileResource(filename); (void) CloseBlob(image); return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P T I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file % format. % % The format of the WritePTIFImage method is: % % MagickBooleanType WritePTIFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info, Image *image) { ExceptionInfo *exception; Image *images, *next, *pyramid_image; ImageInfo *write_info; MagickBooleanType status; PointInfo resolution; size_t columns, rows; /* Create pyramid-encoded TIFF image. */ exception=(&image->exception); images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *clone_image; clone_image=CloneImage(next,0,0,MagickFalse,exception); if (clone_image == (Image *) NULL) break; clone_image->previous=NewImageList(); clone_image->next=NewImageList(); (void) SetImageProperty(clone_image,"tiff:subfiletype","none"); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution.x=next->x_resolution; resolution.y=next->y_resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2.0; resolution.y/=2.0; pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur, exception); if (pyramid_image == (Image *) NULL) break; DestroyBlob(pyramid_image); pyramid_image->blob=ReferenceBlob(next->blob); pyramid_image->x_resolution=resolution.x; pyramid_image->y_resolution=resolution.y; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE"); AppendImageToList(&images,pyramid_image); } } status=MagickFalse; if (images != (Image *) NULL) { /* Write pyramid-encoded TIFF image. */ images=GetFirstImageInList(images); write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; status=WriteTIFFImage(write_info,images); images=DestroyImageList(images); write_info=DestroyImageInfo(write_info); } return(status); } #endif #if defined(MAGICKCORE_TIFF_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W r i t e T I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTIFFImage() writes an image in the Tagged image file format. % % The format of the WriteTIFFImage method is: % % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ typedef struct _TIFFInfo { RectangleInfo tile_geometry; unsigned char *scanline, *scanlines, *pixels; } TIFFInfo; static void DestroyTIFFInfo(TIFFInfo *tiff_info) { assert(tiff_info != (TIFFInfo *) NULL); if (tiff_info->scanlines != (unsigned char *) NULL) tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory( tiff_info->scanlines); if (tiff_info->pixels != (unsigned char *) NULL) tiff_info->pixels=(unsigned char *) RelinquishMagickMemory( tiff_info->pixels); } static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(q)-0.5; if (b < 0.0) b+=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; break; } } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff, TIFFInfo *tiff_info) { const char *option; MagickStatusType flags; uint32 tile_columns, tile_rows; assert(tiff_info != (TIFFInfo *) NULL); (void) memset(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) { uint32 rows_per_strip; option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); else if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0) rows_per_strip=0; /* use default */ rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); return(MagickTrue); } flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry); if ((flags & HeightValue) == 0) tiff_info->tile_geometry.height=tiff_info->tile_geometry.width; tile_columns=(uint32) tiff_info->tile_geometry.width; tile_rows=(uint32) tiff_info->tile_geometry.height; TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows); (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns); (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows); tiff_info->tile_geometry.width=tile_columns; tiff_info->tile_geometry.height=tile_rows; if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines)); tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t) tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines)); if ((tiff_info->scanlines == (unsigned char *) NULL) || (tiff_info->pixels == (unsigned char *) NULL)) { DestroyTIFFInfo(tiff_info); return(MagickFalse); } return(MagickTrue); } static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row, tsample_t sample,Image *image) { int32 status; register ssize_t i; register unsigned char *p, *q; size_t number_tiles, tile_width; ssize_t bytes_per_pixel, j, k, l; if (TIFFIsTiled(tiff) == 0) return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample)); /* Fill scanlines to tile height. */ i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff); (void) memcpy(tiff_info->scanlines+i,(char *) tiff_info->scanline, (size_t) TIFFScanlineSize(tiff)); if (((size_t) (row % tiff_info->tile_geometry.height) != (tiff_info->tile_geometry.height-1)) && (row != (ssize_t) (image->rows-1))) return(0); /* Write tile to TIFF image. */ status=0; bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height* tiff_info->tile_geometry.width); number_tiles=(image->columns+tiff_info->tile_geometry.width)/ tiff_info->tile_geometry.width; for (i=0; i < (ssize_t) number_tiles; i++) { tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i* tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width; for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++) for (k=0; k < (ssize_t) tile_width; k++) { if (bytes_per_pixel == 0) { p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)/8); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8); *q++=(*p++); continue; } p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i* tiff_info->tile_geometry.width+k)*bytes_per_pixel); q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel); for (l=0; l < bytes_per_pixel; l++) *q++=(*p++); } if ((i*tiff_info->tile_geometry.width) != image->columns) status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i* tiff_info->tile_geometry.width),(uint32) ((row/ tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0, sample); if (status < 0) break; } return(status); } static void TIFFSetProfiles(TIFF *tiff,Image *image) { const char *name; const StringInfo *profile; if (image->profiles == (void *) NULL) return; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (GetStringInfoLength(profile) == 0) { name=GetNextImageProfile(image); continue; } #if defined(TIFFTAG_XMLPACKET) if (LocaleCompare(name,"xmp") == 0) (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif #if defined(TIFFTAG_ICCPROFILE) if (LocaleCompare(name,"icc") == 0) (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength( profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"iptc") == 0) { size_t length; StringInfo *iptc_profile; iptc_profile=CloneStringInfo(profile); length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) & 0x03); SetStringInfoLength(iptc_profile,length); if (TIFFIsByteSwapped(tiff)) TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile), (unsigned long) (length/4)); (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32) GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile)); iptc_profile=DestroyStringInfo(iptc_profile); } #if defined(TIFFTAG_PHOTOSHOP) if (LocaleCompare(name,"8bim") == 0) (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32) GetStringInfoLength(profile),GetStringInfoDatum(profile)); #endif if (LocaleCompare(name,"tiff:37724") == 0) (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (LocaleCompare(name,"tiff:34118") == 0) (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info, Image *image) { const char *value; value=GetImageArtifact(image,"tiff:document"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value); value=GetImageArtifact(image,"tiff:hostcomputer"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value); value=GetImageArtifact(image,"tiff:artist"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value); value=GetImageArtifact(image,"tiff:timestamp"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value); value=GetImageArtifact(image,"tiff:make"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MAKE,value); value=GetImageArtifact(image,"tiff:model"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_MODEL,value); value=GetImageArtifact(image,"tiff:software"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value); value=GetImageArtifact(image,"tiff:copyright"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value); value=GetImageArtifact(image,"kodak-33423"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,33423,value); value=GetImageArtifact(image,"kodak-36867"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,36867,value); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value); value=GetImageArtifact(image,"tiff:subfiletype"); if (value != (const char *) NULL) { if (LocaleCompare(value,"REDUCEDIMAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); else if (LocaleCompare(value,"PAGE") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); else if (LocaleCompare(value,"MASK") == 0) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK); } else { uint16 page, pages; page=(uint16) image->scene; pages=(uint16) GetImageListLength(image); if ((image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } } static void TIFFSetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) const char *value; register ssize_t i; uint32 offset; /* Write EXIF properties. */ offset=0; (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset); for (i=0; exif_info[i].tag != 0; i++) { value=GetImageProperty(image,exif_info[i].property); if (value == (const char *) NULL) continue; switch (exif_info[i].type) { case TIFF_ASCII: { (void) TIFFSetField(tiff,exif_info[i].tag,value); break; } case TIFF_SHORT: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_LONG: { uint16 field; field=(uint16) StringToLong(value); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } case TIFF_RATIONAL: case TIFF_SRATIONAL: { float field; field=StringToDouble(value,(char **) NULL); (void) TIFFSetField(tiff,exif_info[i].tag,field); break; } default: break; } } /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */ #else (void) tiff; (void) image; #endif } static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF 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); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); if (image->exception.severity > ErrorException) { TIFFClose(tiff); return(MagickFalse); } (void) DeleteImageProfile(image,"tiff:37724"); scene=0; debug=IsEventLogging(); (void) debug; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; option=GetImageOption(image_info,"quantum:polarity"); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; option=GetImageOption(image_info,"quantum:polarity"); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } #if defined(COMPRESSION_WEBP) case WebPCompression: { compress_tag=COMPRESSION_WEBP; break; } #endif case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } #if defined(COMPRESSION_ZSTD) case ZstdCompression: { compress_tag=COMPRESSION_ZSTD; break; } #endif case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) || (compress_tag == COMPRESSION_CCITTFAX4)) { if ((photometric != PHOTOMETRIC_MINISWHITE) && (photometric != PHOTOMETRIC_MINISBLACK)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } #if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality); if (image_info->quality >= 100) (void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1); break; } #endif #if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/ 100.0); break; } #endif default: break; } option=GetImageOption(image_info,"tiff:predictor"); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); else (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; 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; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); if (image->exception.severity > ErrorException) break; DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1018_0
crossvul-cpp_data_good_351_3
/* * card-cac.c: Support for CAC from NIST SP800-73 * 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 /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return 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 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; 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_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* 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); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* 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); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * 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, int type) { 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->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], 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, sc_key_select 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. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { 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 */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* 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; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } 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); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* 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; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, 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, card->type); } 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 the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } 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, SC_CARD_TYPE_CAC_II); } /* * 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) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(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 = cac_labels[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); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * 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 = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 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; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * 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-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* 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 Alt"); 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_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; 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) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, 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; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_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.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_3
crossvul-cpp_data_bad_2734_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 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://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/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.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/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.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/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/transform.h" #include "magick/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelPackets all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketOpacity(pixelpacket) \ (pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketOpacity((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed((pixel), \ ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelGreen(pixel) \ (SetPixelGreen((pixel), \ ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelBlue(pixel) \ (SetPixelBlue((pixel), \ ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelOpacity(pixel) \ (SetPixelOpacity((pixel), \ ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBO(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelOpacity((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \ (pixelpacket).opacity=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketOpacity((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xc0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xc0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02Opacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \ SetPixelOpacity((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBO(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02Opacity((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xe0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xe0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelBlue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \ & 0xe0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelRGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03PixelGreen((pixel)); \ LBR03PixelBlue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \ (pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketOpacity((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xf0; \ SetPixelRed((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xf0; \ SetPixelGreen((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \ SetPixelBlue((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelOpacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \ SetPixelOpacity((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBO(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelOpacity((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelPacket mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const PixelPacket *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p++; } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without loss of info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(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 IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(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 IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(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 IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(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. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { Image *image; image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError, message,"`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { Image *image; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. */ LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; int i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; /* copy chunk->data to profile */ s=chunk->data; for (i=0; i < (ssize_t) chunk->size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); /* Return one of the following: */ /* return(-n); chunk had an error */ /* return(0); did not recognize */ /* return(n); success */ return(1); } return(0); /* Did not recognize */ } #endif #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) 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 ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; LongPixelPacket transparent_color; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; ssize_t ping_rowbytes, y; register unsigned char *p; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif image=mng_info->image; if (logging != MagickFalse) { (void)LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->matte=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->matte, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.opacity=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) InheritException(exception,&image->exception); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { /* Ignore the iCCP chunk */ png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for exIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1); png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED #if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); #endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); /* Read and check IHDR chunk data */ png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->x_resolution=(double) x_resolution; image->y_resolution=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) x_resolution/100.0; image->y_resolution=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) if (mng_info->global_trns_length) { if (mng_info->global_trns_length > mng_info->global_plte_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n" " bkgd_scale=%d. ping_background=(%d,%d,%d).", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.opacity=OpaqueOpacity; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->matte=MagickFalse; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.opacity= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", ping_trans_color->gray,transparent_color.opacity); } transparent_color.red=transparent_color.opacity; transparent_color.green=transparent_color.opacity; transparent_color.blue=transparent_color.opacity; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = 65535/((1UL << ping_file_depth)-1); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MaxTextExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MaxTextExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method",msg); if (number_colors != 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; else { if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); } if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelOpacity(q) != OpaqueOpacity)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q++; } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? MagickTrue : MagickFalse; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->matte ? 2 : 1)*sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; /* In image.h, OpaqueOpacity is 0 * TransparentOpacity is QuantumRange * In a PNG datastream, Opaque is QuantumRange * and Transparent is 0. */ alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) size_t quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { alpha=*p++; SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; p++; q++; } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*r++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->matte=found_transparent_pixel; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } if (image->storage_class == PseudoClass) { MagickBooleanType matte; matte=image->matte; image->matte=MagickFalse; (void) SyncImage(image); image->matte=matte; } png_read_end(ping,end_info); if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->matte=MagickTrue; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].opacity = ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x])); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.opacity) { image->colormap[x].opacity = (Quantum) TransparentOpacity; } } } (void) SyncImage(image); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue) { SetPixelOpacity(q,TransparentOpacity); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelOpacity(q)=(Quantum) OpaqueOpacity; } #endif q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } if ((ping_color_type == PNG_COLOR_TYPE_GRAY) || (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*value)); if (value == (char *) NULL) png_error(ping,"Memory allocation failed"); *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, &image->exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->matte to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->matte != MagickFalse) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleMatteType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteMatteType); else (void) SetImageType(image,TrueColorMatteType); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType); else (void) SetImageType(image,TrueColorType); } #endif /* Set more properties for identify to retrieve */ { char msg[MaxTextExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MaxTextExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MaxTextExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg); } (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found"); /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg); if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MaxTextExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* 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); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { if (color_image != (Image *) NULL) color_image=DestroyImage(color_image); if (color_image_info != (ImageInfo *) NULL) color_image_info=DestroyImageInfo(color_image_info); ThrowReaderException(CorruptImageError,"CorruptImage"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(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 *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG 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 RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MaxTextExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MaxTextExtent); } #endif entry=SetMagickInfo("MNG"); entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; entry->description=ConstantString("Multiple-image Network Graphics"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("Portable Network Graphics"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG8"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "8-bit indexed with optional binary transparency"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG24"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MaxTextExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,zlib_version,MaxTextExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 24-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG32"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 32-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG48"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 48-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG64"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 64-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG00"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "PNG inheriting bit-depth, color-type from original if possible"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JNG"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("JPEG Network Graphics"); entry->mime_type=ConstantString("image/x-jng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AllocateSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MaxTextExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->magick= %s",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity/2 ? TransparentOpacity : OpaqueOpacity); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",image->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.gray is %d", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using "-define png:compression-strategy", etc., which takes precedence over -quality. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->matte == MagickFalse) { /* Add an opaque matte channel */ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up empty PLTE chunk"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXT chunk with uuencoded ICC"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk with %s profile",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { 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; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { 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; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(image,"png:bit-depth-written",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % To do: Enforce the previous paragraph. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n",mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* To do: use a "LocaleInteger:()" function here. */ /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { Image *jpeg_image; ImageInfo *jpeg_image_info; int unique_filenames; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; unique_filenames=0; status=MagickTrue; transparent=image_info->type==GrayscaleMatteType || image_info->type==TrueColorMatteType || image->matte != MagickFalse; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for opacity."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); status=SeparateImageChannel(jpeg_image,OpacityChannel); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=NegateImage(jpeg_image,MagickFalse); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_image->matte=MagickFalse; jpeg_image_info->type=GrayscaleType; jpeg_image->quality=jng_alpha_quality; (void) SetImageType(jpeg_image,GrayscaleType); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorMatteType && image_info->type != TrueColorType && SetImageGray(image,&image->exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode opacity as a grayscale PNG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); length=0; (void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written"); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode opacity as a grayscale JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating JPEG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->x_resolution && image->y_resolution && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { const char *option; Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->matte) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->matte) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if (next_image->matte || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->matte != MagickFalse) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,&image->exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->x_resolution != next_image->next->x_resolution) || (next_image->y_resolution != next_image->next->y_resolution)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=1UL*image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->x_resolution && image->y_resolution && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && (image->matte || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_eXIf=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2734_0
crossvul-cpp_data_bad_1423_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: readelf.c,v 1.156 2018/10/19 00:33:04 christos Exp $") #endif #ifdef BUILTIN_ELF #include <string.h> #include <ctype.h> #include <stdlib.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "readelf.h" #include "magic.h" #ifdef ELFCORE private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int *, uint16_t *); #endif private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int *, uint16_t *); private int doshn(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int, int *, uint16_t *); private size_t donote(struct magic_set *, void *, size_t, size_t, int, int, size_t, int *, uint16_t *, int, off_t, int, off_t); #define ELF_ALIGN(a) ((((a) + align - 1) / align) * align) #define isquote(c) (strchr("'\"`", (c)) != NULL) private uint16_t getu16(int, uint16_t); private uint32_t getu32(int, uint32_t); private uint64_t getu64(int, uint64_t); #define MAX_PHNUM 128 #define MAX_SHNUM 32768 #define SIZE_UNKNOWN CAST(off_t, -1) private int toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s (%u)", name, num) == -1) return -1; return 1; } private uint16_t getu16(int swap, uint16_t value) { union { uint16_t ui; char c[2]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[1]; retval.c[1] = tmpval.c[0]; return retval.ui; } else return value; } private uint32_t getu32(int swap, uint32_t value) { union { uint32_t ui; char c[4]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[3]; retval.c[1] = tmpval.c[2]; retval.c[2] = tmpval.c[1]; retval.c[3] = tmpval.c[0]; return retval.ui; } else return value; } private uint64_t getu64(int swap, uint64_t value) { union { uint64_t ui; char c[8]; } retval, tmpval; if (swap) { tmpval.ui = value; retval.c[0] = tmpval.c[7]; retval.c[1] = tmpval.c[6]; retval.c[2] = tmpval.c[5]; retval.c[3] = tmpval.c[4]; retval.c[4] = tmpval.c[3]; retval.c[5] = tmpval.c[2]; retval.c[6] = tmpval.c[1]; retval.c[7] = tmpval.c[0]; return retval.ui; } else return value; } #define elf_getu16(swap, value) getu16(swap, value) #define elf_getu32(swap, value) getu32(swap, value) #define elf_getu64(swap, value) getu64(swap, value) #define xsh_addr (clazz == ELFCLASS32 \ ? CAST(void *, &sh32) \ : CAST(void *, &sh64)) #define xsh_sizeof (clazz == ELFCLASS32 \ ? sizeof(sh32) \ : sizeof(sh64)) #define xsh_size CAST(size_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_size) \ : elf_getu64(swap, sh64.sh_size))) #define xsh_offset CAST(off_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_offset) \ : elf_getu64(swap, sh64.sh_offset))) #define xsh_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_type) \ : elf_getu32(swap, sh64.sh_type)) #define xsh_name (clazz == ELFCLASS32 \ ? elf_getu32(swap, sh32.sh_name) \ : elf_getu32(swap, sh64.sh_name)) #define xph_addr (clazz == ELFCLASS32 \ ? CAST(void *, &ph32) \ : CAST(void *, &ph64)) #define xph_sizeof (clazz == ELFCLASS32 \ ? sizeof(ph32) \ : sizeof(ph64)) #define xph_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_type) \ : elf_getu32(swap, ph64.p_type)) #define xph_offset CAST(off_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_offset) \ : elf_getu64(swap, ph64.p_offset))) #define xph_align CAST(size_t, (clazz == ELFCLASS32 \ ? CAST(off_t, (ph32.p_align ? \ elf_getu32(swap, ph32.p_align) : 4))\ : CAST(off_t, (ph64.p_align ? \ elf_getu64(swap, ph64.p_align) : 4)))) #define xph_vaddr CAST(size_t, (clazz == ELFCLASS32 \ ? CAST(off_t, (ph32.p_vaddr ? \ elf_getu32(swap, ph32.p_vaddr) : 4))\ : CAST(off_t, (ph64.p_vaddr ? \ elf_getu64(swap, ph64.p_vaddr) : 4)))) #define xph_filesz CAST(size_t, (clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_filesz) \ : elf_getu64(swap, ph64.p_filesz))) #define xph_memsz CAST(size_t, ((clazz == ELFCLASS32 \ ? elf_getu32(swap, ph32.p_memsz) \ : elf_getu64(swap, ph64.p_memsz)))) #define xnh_addr (clazz == ELFCLASS32 \ ? CAST(void *, &nh32) \ : CAST(void *, &nh64)) #define xnh_sizeof (clazz == ELFCLASS32 \ ? sizeof(nh32) \ : sizeof(nh64)) #define xnh_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_type) \ : elf_getu32(swap, nh64.n_type)) #define xnh_namesz (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_namesz) \ : elf_getu32(swap, nh64.n_namesz)) #define xnh_descsz (clazz == ELFCLASS32 \ ? elf_getu32(swap, nh32.n_descsz) \ : elf_getu32(swap, nh64.n_descsz)) #define xdh_addr (clazz == ELFCLASS32 \ ? CAST(void *, &dh32) \ : CAST(void *, &dh64)) #define xdh_sizeof (clazz == ELFCLASS32 \ ? sizeof(dh32) \ : sizeof(dh64)) #define xdh_tag (clazz == ELFCLASS32 \ ? elf_getu32(swap, dh32.d_tag) \ : elf_getu64(swap, dh64.d_tag)) #define xdh_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, dh32.d_un.d_val) \ : elf_getu64(swap, dh64.d_un.d_val)) #define xcap_addr (clazz == ELFCLASS32 \ ? CAST(void *, &cap32) \ : CAST(void *, &cap64)) #define xcap_sizeof (clazz == ELFCLASS32 \ ? sizeof(cap32) \ : sizeof(cap64)) #define xcap_tag (clazz == ELFCLASS32 \ ? elf_getu32(swap, cap32.c_tag) \ : elf_getu64(swap, cap64.c_tag)) #define xcap_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, cap32.c_un.c_val) \ : elf_getu64(swap, cap64.c_un.c_val)) #define xauxv_addr (clazz == ELFCLASS32 \ ? CAST(void *, &auxv32) \ : CAST(void *, &auxv64)) #define xauxv_sizeof (clazz == ELFCLASS32 \ ? sizeof(auxv32) \ : sizeof(auxv64)) #define xauxv_type (clazz == ELFCLASS32 \ ? elf_getu32(swap, auxv32.a_type) \ : elf_getu64(swap, auxv64.a_type)) #define xauxv_val (clazz == ELFCLASS32 \ ? elf_getu32(swap, auxv32.a_v) \ : elf_getu64(swap, auxv64.a_v)) #define prpsoffsets(i) (clazz == ELFCLASS32 \ ? prpsoffsets32[i] \ : prpsoffsets64[i]) #ifdef ELFCORE /* * Try larger offsets first to avoid false matches * from earlier data that happen to look like strings. */ static const size_t prpsoffsets32[] = { #ifdef USE_NT_PSINFO 104, /* SunOS 5.x (command line) */ 88, /* SunOS 5.x (short name) */ #endif /* USE_NT_PSINFO */ 100, /* SunOS 5.x (command line) */ 84, /* SunOS 5.x (short name) */ 44, /* Linux (command line) */ 28, /* Linux 2.0.36 (short name) */ 8, /* FreeBSD */ }; static const size_t prpsoffsets64[] = { #ifdef USE_NT_PSINFO 152, /* SunOS 5.x (command line) */ 136, /* SunOS 5.x (short name) */ #endif /* USE_NT_PSINFO */ 136, /* SunOS 5.x, 64-bit (command line) */ 120, /* SunOS 5.x, 64-bit (short name) */ 56, /* Linux (command line) */ 40, /* Linux (tested on core from 2.4.x, short name) */ 16, /* FreeBSD, 64-bit */ }; #define NOFFSETS32 (sizeof(prpsoffsets32) / sizeof(prpsoffsets32[0])) #define NOFFSETS64 (sizeof(prpsoffsets64) / sizeof(prpsoffsets64[0])) #define NOFFSETS (clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64) /* * Look through the program headers of an executable image, searching * for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or * "FreeBSD"; if one is found, try looking in various places in its * contents for a 16-character string containing only printable * characters - if found, that string should be the name of the program * that dropped core. Note: right after that 16-character string is, * at least in SunOS 5.x (and possibly other SVR4-flavored systems) and * Linux, a longer string (80 characters, in 5.x, probably other * SVR4-flavored systems, and Linux) containing the start of the * command line for that program. * * SunOS 5.x core files contain two PT_NOTE sections, with the types * NT_PRPSINFO (old) and NT_PSINFO (new). These structs contain the * same info about the command name and command line, so it probably * isn't worthwhile to look for NT_PSINFO, but the offsets are provided * above (see USE_NT_PSINFO), in case we ever decide to do so. The * NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent; * the SunOS 5.x file command relies on this (and prefers the latter). * * The signal number probably appears in a section of type NT_PRSTATUS, * but that's also rather OS-dependent, in ways that are harder to * dissect with heuristics, so I'm not bothering with the signal number. * (I suppose the signal number could be of interest in situations where * you don't have the binary of the program that dropped core; if you * *do* have that binary, the debugger will probably tell you what * signal it was.) */ #define OS_STYLE_SVR4 0 #define OS_STYLE_FREEBSD 1 #define OS_STYLE_NETBSD 2 private const char os_style_names[][8] = { "SVR4", "FreeBSD", "NetBSD", }; #define FLAGS_CORE_STYLE 0x0003 #define FLAGS_DID_CORE 0x0004 #define FLAGS_DID_OS_NOTE 0x0008 #define FLAGS_DID_BUILD_ID 0x0010 #define FLAGS_DID_CORE_STYLE 0x0020 #define FLAGS_DID_NETBSD_PAX 0x0040 #define FLAGS_DID_NETBSD_MARCH 0x0080 #define FLAGS_DID_NETBSD_CMODEL 0x0100 #define FLAGS_DID_NETBSD_EMULATION 0x0200 #define FLAGS_DID_NETBSD_UNKNOWN 0x0400 #define FLAGS_IS_CORE 0x0800 #define FLAGS_DID_AUXV 0x1000 private int dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; off_t ph_off = off; int ph_num = num; if (num == 0) { if (file_printf(ms, ", no program header") == -1) return -1; return 0; } if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < CAST(ssize_t, xph_sizeof)) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags, notecount, fd, ph_off, ph_num, fsize); if (offset == 0) break; } } return 0; } #endif static void do_note_netbsd_version(struct magic_set *ms, int swap, void *v) { uint32_t desc; memcpy(&desc, v, sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, ", for NetBSD") == -1) return; /* * The version number used to be stuck as 199905, and was thus * basically content-free. Newer versions of NetBSD have fixed * this and now use the encoding of __NetBSD_Version__: * * MMmmrrpp00 * * M = major version * m = minor version * r = release ["",A-Z,Z[A-Z] but numeric] * p = patchlevel */ if (desc > 100000000U) { uint32_t ver_patch = (desc / 100) % 100; uint32_t ver_rel = (desc / 10000) % 100; uint32_t ver_min = (desc / 1000000) % 100; uint32_t ver_maj = desc / 100000000; if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1) return; if (ver_rel == 0 && ver_patch != 0) { if (file_printf(ms, ".%u", ver_patch) == -1) return; } else if (ver_rel != 0) { while (ver_rel > 26) { if (file_printf(ms, "Z") == -1) return; ver_rel -= 26; } if (file_printf(ms, "%c", 'A' + ver_rel - 1) == -1) return; } } } static void do_note_freebsd_version(struct magic_set *ms, int swap, void *v) { uint32_t desc; memcpy(&desc, v, sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, ", for FreeBSD") == -1) return; /* * Contents is __FreeBSD_version, whose relation to OS * versions is defined by a huge table in the Porter's * Handbook. This is the general scheme: * * Releases: * Mmp000 (before 4.10) * Mmi0p0 (before 5.0) * Mmm0p0 * * Development branches: * Mmpxxx (before 4.6) * Mmp1xx (before 4.10) * Mmi1xx (before 5.0) * M000xx (pre-M.0) * Mmm1xx * * M = major version * m = minor version * i = minor version increment (491000 -> 4.10) * p = patchlevel * x = revision * * The first release of FreeBSD to use ELF by default * was version 3.0. */ if (desc == 460002) { if (file_printf(ms, " 4.6.2") == -1) return; } else if (desc < 460100) { if (file_printf(ms, " %d.%d", desc / 100000, desc / 10000 % 10) == -1) return; if (desc / 1000 % 10 > 0) if (file_printf(ms, ".%d", desc / 1000 % 10) == -1) return; if ((desc % 1000 > 0) || (desc % 100000 == 0)) if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc < 500000) { if (file_printf(ms, " %d.%d", desc / 100000, desc / 10000 % 10 + desc / 1000 % 10) == -1) return; if (desc / 100 % 10 > 0) { if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc / 10 % 10 > 0) { if (file_printf(ms, ".%d", desc / 10 % 10) == -1) return; } } else { if (file_printf(ms, " %d.%d", desc / 100000, desc / 1000 % 100) == -1) return; if ((desc / 100 % 10 > 0) || (desc % 100000 / 100 == 0)) { if (file_printf(ms, " (%d)", desc) == -1) return; } else if (desc / 10 % 10 > 0) { if (file_printf(ms, ".%d", desc / 10 % 10) == -1) return; } } } private int /*ARGSUSED*/ do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) { uint8_t desc[20]; const char *btype; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; switch (descsz) { case 8: btype = "xxHash"; break; case 16: btype = "md5/uuid"; break; case 20: btype = "sha1"; break; default: btype = "unknown"; break; } if (file_printf(ms, ", BuildID[%s]=", btype) == -1) return 1; memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "Go") == 0 && type == NT_GO_BUILD_ID && descsz < 128) { if (file_printf(ms, ", Go BuildID=%s", (char *)&nbuf[doff]) == -1) return -1; return 1; } return 0; } private int do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 && type == NT_GNU_VERSION && descsz == 2) { *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]) == -1) return -1; return 1; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_VERSION && descsz == 16) { uint32_t desc[4]; memcpy(desc, &nbuf[doff], sizeof(desc)); *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for GNU/") == -1) return 1; switch (elf_getu32(swap, desc[0])) { case GNU_OS_LINUX: if (file_printf(ms, "Linux") == -1) return 1; break; case GNU_OS_HURD: if (file_printf(ms, "Hurd") == -1) return 1; break; case GNU_OS_SOLARIS: if (file_printf(ms, "Solaris") == -1) return 1; break; case GNU_OS_KFREEBSD: if (file_printf(ms, "kFreeBSD") == -1) return 1; break; case GNU_OS_KNETBSD: if (file_printf(ms, "kNetBSD") == -1) return 1; break; default: if (file_printf(ms, "<unknown>") == -1) return 1; } if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]), elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) return 1; return 1; } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { if (type == NT_NETBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_netbsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) { if (type == NT_FREEBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_freebsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 && type == NT_OPENBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for OpenBSD") == -1) return 1; /* Content of note is always 0 */ return 1; } if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 && type == NT_DRAGONFLY_VERSION && descsz == 4) { uint32_t desc; *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for DragonFly") == -1) return 1; memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, " %d.%d.%d", desc / 100000, desc / 10000 % 10, desc % 10000) == -1) return 1; return 1; } return 0; } private int do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 && type == NT_NETBSD_PAX && descsz == 4) { static const char *pax[] = { "+mprotect", "-mprotect", "+segvguard", "-segvguard", "+ASLR", "-ASLR", }; uint32_t desc; size_t i; int did = 0; *flags |= FLAGS_DID_NETBSD_PAX; memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (desc && file_printf(ms, ", PaX: ") == -1) return 1; for (i = 0; i < __arraycount(pax); i++) { if (((1 << (int)i) & desc) == 0) continue; if (file_printf(ms, "%s%s", did++ ? "," : "", pax[i]) == -1) return 1; } return 1; } return 0; } private int do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, descsz); if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, " "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)", file_printable(sbuf, sizeof(sbuf), RCAST(char *, pi.cpi_name)), elf_getu32(swap, (uint32_t)pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, (uint32_t)pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; case OS_STYLE_FREEBSD: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t argoff, pidoff; if (clazz == ELFCLASS32) argoff = 4 + 4 + 17; else argoff = 4 + 4 + 8 + 17; if (file_printf(ms, ", from '%.80s'", nbuf + doff + argoff) == -1) return 1; pidoff = argoff + 81 + 2; if (doff + pidoff + 4 <= size) { if (file_printf(ms, ", pid=%u", elf_getu32(swap, *RCAST(uint32_t *, (nbuf + doff + pidoff)))) == -1) return 1; } *flags |= FLAGS_DID_CORE; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; cp < nbuf + size && *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; } private off_t get_offset_from_virtaddr(struct magic_set *ms, int swap, int clazz, int fd, off_t off, int num, off_t fsize, uint64_t virtaddr) { Elf32_Phdr ph32; Elf64_Phdr ph64; /* * Loop through all the program headers and find the header with * virtual address in which the "virtaddr" belongs to. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += xph_sizeof; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (virtaddr >= xph_vaddr && virtaddr < xph_vaddr + xph_filesz) return xph_offset + (virtaddr - xph_vaddr); } return 0; } private size_t get_string_on_virtaddr(struct magic_set *ms, int swap, int clazz, int fd, off_t ph_off, int ph_num, off_t fsize, uint64_t virtaddr, char *buf, ssize_t buflen) { char *bptr; off_t offset; if (buflen == 0) return 0; offset = get_offset_from_virtaddr(ms, swap, clazz, fd, ph_off, ph_num, fsize, virtaddr); if (offset < 0 || (buflen = pread(fd, buf, CAST(size_t, buflen), offset)) <= 0) { file_badread(ms); return 0; } buf[buflen - 1] = '\0'; /* We expect only printable characters, so return if buffer contains * non-printable character before the '\0' or just '\0'. */ for (bptr = buf; *bptr && isprint((unsigned char)*bptr); bptr++) continue; if (*bptr != '\0') return 0; return bptr - buf; } /*ARGSUSED*/ private int do_auxv_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz __attribute__((__unused__)), uint32_t descsz __attribute__((__unused__)), size_t noff __attribute__((__unused__)), size_t doff, int *flags, size_t size __attribute__((__unused__)), int clazz, int fd, off_t ph_off, int ph_num, off_t fsize) { #ifdef ELFCORE Aux32Info auxv32; Aux64Info auxv64; size_t elsize = xauxv_sizeof; const char *tag; int is_string; size_t nval; if ((*flags & (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) != (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) return 0; switch (*flags & FLAGS_CORE_STYLE) { case OS_STYLE_SVR4: if (type != NT_AUXV) return 0; break; #ifdef notyet case OS_STYLE_NETBSD: if (type != NT_NETBSD_CORE_AUXV) return 0; break; case OS_STYLE_FREEBSD: if (type != NT_FREEBSD_PROCSTAT_AUXV) return 0; break; #endif default: return 0; } *flags |= FLAGS_DID_AUXV; nval = 0; for (size_t off = 0; off + elsize <= descsz; off += elsize) { memcpy(xauxv_addr, &nbuf[doff + off], xauxv_sizeof); /* Limit processing to 50 vector entries to prevent DoS */ if (nval++ >= 50) { file_error(ms, 0, "Too many ELF Auxv elements"); return 1; } switch(xauxv_type) { case AT_LINUX_EXECFN: is_string = 1; tag = "execfn"; break; case AT_LINUX_PLATFORM: is_string = 1; tag = "platform"; break; case AT_LINUX_UID: is_string = 0; tag = "real uid"; break; case AT_LINUX_GID: is_string = 0; tag = "real gid"; break; case AT_LINUX_EUID: is_string = 0; tag = "effective uid"; break; case AT_LINUX_EGID: is_string = 0; tag = "effective gid"; break; default: is_string = 0; tag = NULL; break; } if (tag == NULL) continue; if (is_string) { char buf[256]; ssize_t buflen; buflen = get_string_on_virtaddr(ms, swap, clazz, fd, ph_off, ph_num, fsize, xauxv_val, buf, sizeof(buf)); if (buflen == 0) continue; if (file_printf(ms, ", %s: '%s'", tag, buf) == -1) return 0; } else { if (file_printf(ms, ", %s: %d", tag, (int) xauxv_val) == -1) return 0; } } return 1; #else return 0; #endif } private size_t dodynamic(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap) { Elf32_Dyn dh32; Elf64_Dyn dh64; unsigned char *dbuf = CAST(unsigned char *, vbuf); if (xdh_sizeof + offset > size) { /* * We're out of note headers. */ return xdh_sizeof + offset; } memcpy(xdh_addr, &dbuf[offset], xdh_sizeof); offset += xdh_sizeof; switch (xdh_tag) { case DT_FLAGS_1: if (xdh_val == DF_1_PIE) ms->mode |= 0111; else ms->mode &= ~0111; break; default: break; } return offset; } private size_t donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags, uint16_t *notecount, int fd, off_t ph_off, int ph_num, off_t fsize) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); if (*notecount == 0) return 0; --*notecount; if (xnh_sizeof + offset > size) { /* * We're out of note headers. */ return xnh_sizeof + offset; } memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { if (file_printf(ms, ", bad note name size %#lx", CAST(unsigned long, namesz)) == -1) return 0; return 0; } if (descsz & 0x80000000) { if (file_printf(ms, ", bad note description size %#lx", CAST(unsigned long, descsz)) == -1) return 0; return 0; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & FLAGS_DID_OS_NOTE) == 0) { if (do_os_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_BUILD_ID) == 0) { if (do_bid_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { if (do_pax_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return offset; } if ((*flags & FLAGS_DID_CORE) == 0) { if (do_core_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz)) return offset; } if ((*flags & FLAGS_DID_AUXV) == 0) { if (do_auxv_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz, fd, ph_off, ph_num, fsize)) return offset; } if (namesz == 7 && strcmp(RCAST(char *, &nbuf[noff]), "NetBSD") == 0) { int descw, flag; const char *str, *tag; if (descsz > 100) descsz = 100; switch (xnh_type) { case NT_NETBSD_VERSION: return offset; case NT_NETBSD_MARCH: flag = FLAGS_DID_NETBSD_MARCH; tag = "compiled for"; break; case NT_NETBSD_CMODEL: flag = FLAGS_DID_NETBSD_CMODEL; tag = "compiler model"; break; case NT_NETBSD_EMULATION: flag = FLAGS_DID_NETBSD_EMULATION; tag = "emulation:"; break; default: if (*flags & FLAGS_DID_NETBSD_UNKNOWN) return offset; *flags |= FLAGS_DID_NETBSD_UNKNOWN; if (file_printf(ms, ", note=%u", xnh_type) == -1) return offset; return offset; } if (*flags & flag) return offset; str = RCAST(const char *, &nbuf[doff]); descw = CAST(int, descsz); *flags |= flag; file_printf(ms, ", %s: %.*s", tag, descw, str); return offset; } return offset; } /* SunOS 5.x hardware capability descriptions */ typedef struct cap_desc { uint64_t cd_mask; const char *cd_name; } cap_desc_t; static const cap_desc_t cap_desc_sparc[] = { { AV_SPARC_MUL32, "MUL32" }, { AV_SPARC_DIV32, "DIV32" }, { AV_SPARC_FSMULD, "FSMULD" }, { AV_SPARC_V8PLUS, "V8PLUS" }, { AV_SPARC_POPC, "POPC" }, { AV_SPARC_VIS, "VIS" }, { AV_SPARC_VIS2, "VIS2" }, { AV_SPARC_ASI_BLK_INIT, "ASI_BLK_INIT" }, { AV_SPARC_FMAF, "FMAF" }, { AV_SPARC_FJFMAU, "FJFMAU" }, { AV_SPARC_IMA, "IMA" }, { 0, NULL } }; static const cap_desc_t cap_desc_386[] = { { AV_386_FPU, "FPU" }, { AV_386_TSC, "TSC" }, { AV_386_CX8, "CX8" }, { AV_386_SEP, "SEP" }, { AV_386_AMD_SYSC, "AMD_SYSC" }, { AV_386_CMOV, "CMOV" }, { AV_386_MMX, "MMX" }, { AV_386_AMD_MMX, "AMD_MMX" }, { AV_386_AMD_3DNow, "AMD_3DNow" }, { AV_386_AMD_3DNowx, "AMD_3DNowx" }, { AV_386_FXSR, "FXSR" }, { AV_386_SSE, "SSE" }, { AV_386_SSE2, "SSE2" }, { AV_386_PAUSE, "PAUSE" }, { AV_386_SSE3, "SSE3" }, { AV_386_MON, "MON" }, { AV_386_CX16, "CX16" }, { AV_386_AHF, "AHF" }, { AV_386_TSCP, "TSCP" }, { AV_386_AMD_SSE4A, "AMD_SSE4A" }, { AV_386_POPCNT, "POPCNT" }, { AV_386_AMD_LZCNT, "AMD_LZCNT" }, { AV_386_SSSE3, "SSSE3" }, { AV_386_SSE4_1, "SSE4.1" }, { AV_386_SSE4_2, "SSE4.2" }, { 0, NULL } }; private int doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int mach, int strtab, int *flags, uint16_t *notecount) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1, has_debug_info = 0; size_t nbadcap = 0; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */ char name[50]; ssize_t namesize; if (num == 0) { if (file_printf(ms, ", no section header") == -1) return -1; return 0; } if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) < CAST(ssize_t, xsh_sizeof)) { if (file_printf(ms, ", missing section headers") == -1) return -1; return 0; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { file_badread(ms); return -1; } name[namesize] = '\0'; if (strcmp(name, ".debug_info") == 0) { has_debug_info = 1; stripped = 0; } if (pread(fd, xsh_addr, xsh_sizeof, off) < CAST(ssize_t, xsh_sizeof)) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if (CAST(uintmax_t, (xsh_size + xsh_offset)) > CAST(uintmax_t, fsize)) { if (file_printf(ms, ", note offset/size %#" INTMAX_T_FORMAT "x+%#" INTMAX_T_FORMAT "x exceeds" " file size %#" INTMAX_T_FORMAT "x", CAST(uintmax_t, xsh_offset), CAST(uintmax_t, xsh_size), CAST(uintmax_t, fsize)) == -1) return -1; return 0; } if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) < CAST(ssize_t, xsh_size)) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= CAST(off_t, xsh_size)) break; noff = donote(ms, nbuf, CAST(size_t, noff), xsh_size, clazz, swap, 4, flags, notecount, fd, 0, 0, 0); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (nbadcap > 5) break; if (lseek(fd, xsh_offset, SEEK_SET) == CAST(off_t, -1)) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof(cap32), sizeof(cap64))]; if ((coff += xcap_sizeof) > CAST(off_t, xsh_size)) break; if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) != CAST(ssize_t, xcap_sizeof)) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } // gnu attributes #endif break; } memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "%#" INT64_T_FORMAT "x = %#" INT64_T_FORMAT "x", CAST(unsigned long long, xcap_tag), CAST(unsigned long long, xcap_val)) == -1) return -1; if (nbadcap++ > 2) coff = xsh_size; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (has_debug_info) { if (file_printf(ms, ", with debug_info") == -1) return -1; } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability %#" INT64_T_FORMAT "x", CAST(unsigned long long, cap_hw1)) == -1) return -1; } else { if (file_printf(ms, " hardware capability %#" INT64_T_FORMAT "x", CAST(unsigned long long, cap_hw1)) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability %#" INT64_T_FORMAT "x", CAST(unsigned long long, cap_sf1)) == -1) return -1; } return 0; } /* * Look through the program headers of an executable image, searching * for a PT_INTERP section; if one is found, it's dynamically linked, * otherwise it's statically linked. */ private int dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int sh_num, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; char interp[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (num == 0) { if (file_printf(ms, ", no program header") == -1) return -1; return 0; } if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } interp[0] = '\0'; for ( ; num; num--) { int doread; if (pread(fd, xph_addr, xph_sizeof, off) < CAST(ssize_t, xph_sizeof)) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; doread = 1; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment %#lx", CAST(unsigned long, align)) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: doread = 1; break; default: doread = 0; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } if (doread) { len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } } else len = 0; /* Things we can determine when we seek */ switch (xph_type) { case PT_DYNAMIC: offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = dodynamic(ms, nbuf, offset, CAST(size_t, bufsize), clazz, swap); if (offset == 0) break; } break; case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; memcpy(interp, nbuf, (size_t)bufsize); } else strlcpy(interp, "*empty*", sizeof(interp)); break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, CAST(size_t, bufsize), clazz, swap, align, flags, notecount, fd, 0, 0, 0); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; } protected int file_tryelf(struct magic_set *ms, const struct buffer *b) { int fd = b->fd; const unsigned char *buf = CAST(const unsigned char *, b->fbuf); size_t nbytes = b->flen; union { int32_t l; char c[sizeof(int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum, notecount; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE|MAGIC_EXTENSION)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless * needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, CAST(off_t, 0), SEEK_SET) == CAST(off_t, -1)) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fd == -1 || fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1423_0
crossvul-cpp_data_bad_372_0
/* * Copyright 2013-2014 MongoDB, Inc. * * 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. */ #include "bson/bson-iter.h" #include "bson/bson-config.h" #include "bson/bson-decimal128.h" #include "bson-types.h" #define ITER_TYPE(i) ((bson_type_t) * ((i)->raw + (i)->type)) /* *-------------------------------------------------------------------------- * * bson_iter_init -- * * Initializes @iter to be used to iterate @bson. * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init (bson_iter_t *iter, /* OUT */ const bson_t *bson) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); if (BSON_UNLIKELY (bson->len < 5)) { memset (iter, 0, sizeof *iter); return false; } iter->raw = bson_get_data (bson); iter->len = bson->len; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_from_data -- * * Initializes @iter to be used to iterate @data of length @length * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init_from_data (bson_iter_t *iter, /* OUT */ const uint8_t *data, /* IN */ size_t length) /* IN */ { uint32_t len_le; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } memcpy (&len_le, data, sizeof (len_le)); if (BSON_UNLIKELY ((size_t) BSON_UINT32_FROM_LE (len_le) != length)) { memset (iter, 0, sizeof *iter); return false; } if (BSON_UNLIKELY (data[length - 1])) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = length; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_recurse -- * * Creates a new sub-iter looking at the document or array that @iter * is currently pointing at. * * Returns: * true if successful and @child was initialized. * * Side effects: * @child is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_recurse (const bson_iter_t *iter, /* IN */ bson_iter_t *child) /* OUT */ { const uint8_t *data = NULL; uint32_t len = 0; BSON_ASSERT (iter); BSON_ASSERT (child); if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { bson_iter_document (iter, &len, &data); } else if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { bson_iter_array (iter, &len, &data); } else { return false; } child->raw = data; child->len = len; child->off = 0; child->type = 0; child->key = 0; child->d1 = 0; child->d2 = 0; child->d3 = 0; child->d4 = 0; child->next_off = 4; child->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_find -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_w_len -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_w_len (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key, /* IN */ int keylen) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_w_len (iter, key, keylen); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_case -- * * A case-insensitive version of bson_iter_init_find(). * * Returns: * true if the field was found and @iter is observing that field. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_case (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_case (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_find_w_len -- * * Searches through @iter starting from the current position for a key * matching @key. @keylen indicates the length of @key, or -1 to * determine the length with strlen(). * * Returns: * true if the field @key was found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_w_len (bson_iter_t *iter, /* INOUT */ const char *key, /* IN */ int keylen) /* IN */ { const char *ikey; if (keylen < 0) { keylen = (int) strlen (key); } while (bson_iter_next (iter)) { ikey = bson_iter_key (iter); if ((0 == strncmp (key, ikey, keylen)) && (ikey[keylen] == '\0')) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-sensitive search meaning "KEY" and * "key" would NOT match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); return bson_iter_find_w_len (iter, key, -1); } /* *-------------------------------------------------------------------------- * * bson_iter_find_case -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-insensitive search meaning "KEY" and * "key" would match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_case (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); while (bson_iter_next (iter)) { if (!bson_strcasecmp (key, bson_iter_key (iter))) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find_descendant -- * * Locates a descendant using the "parent.child.key" notation. This * operates similar to bson_iter_find() except that it can recurse * into children documents using the dot notation. * * Returns: * true if the descendant was found and @descendant was initialized. * * Side effects: * @descendant may be initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_find_descendant (bson_iter_t *iter, /* INOUT */ const char *dotkey, /* IN */ bson_iter_t *descendant) /* OUT */ { bson_iter_t tmp; const char *dot; size_t sublen; BSON_ASSERT (iter); BSON_ASSERT (dotkey); BSON_ASSERT (descendant); if ((dot = strchr (dotkey, '.'))) { sublen = dot - dotkey; } else { sublen = strlen (dotkey); } if (bson_iter_find_w_len (iter, dotkey, (int) sublen)) { if (!dot) { *descendant = *iter; return true; } if (BSON_ITER_HOLDS_DOCUMENT (iter) || BSON_ITER_HOLDS_ARRAY (iter)) { if (bson_iter_recurse (iter, &tmp)) { return bson_iter_find_descendant (&tmp, dot + 1, descendant); } } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_key -- * * Retrieves the key of the current field. The resulting key is valid * while @iter is valid. * * Returns: * A string that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_key (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); return bson_iter_key_unsafe (iter); } /* *-------------------------------------------------------------------------- * * bson_iter_type -- * * Retrieves the type of the current field. It may be useful to check * the type using the BSON_ITER_HOLDS_*() macros. * * Returns: * A bson_type_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bson_type_t bson_iter_type (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (iter->raw); BSON_ASSERT (iter->len); return bson_iter_type_unsafe (iter); } /* *-------------------------------------------------------------------------- * * _bson_iter_next_internal -- * * Internal function to advance @iter to the next field and retrieve * the key and BSON type before error-checking. @next_keylen is * the key length of the next field being iterated or 0 if this is * not known. * * Return: * true if an element was decoded, else false. * * Side effects: * @key and @bson_type are set. * * If the return value is false: * - @iter is invalidated: @iter->raw is NULLed * - @unsupported is set to true if the bson type is unsupported * - otherwise if the BSON is corrupt, @iter->err_off is nonzero * - otherwise @bson_type is set to BSON_TYPE_EOD * *-------------------------------------------------------------------------- */ static bool _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; } /* *-------------------------------------------------------------------------- * * bson_iter_next -- * * Advances @iter to the next field of the underlying BSON document. * If all fields have been exhausted, then %false is returned. * * It is a programming error to use @iter after this function has * returned false. * * Returns: * true if the iter was advanced to the next record. * otherwise false and @iter should be considered invalid. * * Side effects: * @iter may be invalidated. * *-------------------------------------------------------------------------- */ bool bson_iter_next (bson_iter_t *iter) /* INOUT */ { uint32_t bson_type; const char *key; bool unsupported; return _bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported); } /* *-------------------------------------------------------------------------- * * bson_iter_binary -- * * Retrieves the BSON_TYPE_BINARY field. The subtype is stored in * @subtype. The length of @binary in bytes is stored in @binary_len. * * @binary should not be modified or freed and is only valid while * @iter's bson_t is valid and unmodified. * * Parameters: * @iter: A bson_iter_t * @subtype: A location for the binary subtype. * @binary_len: A location for the length of @binary. * @binary: A location for a pointer to the binary data. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_binary (const bson_iter_t *iter, /* IN */ bson_subtype_t *subtype, /* OUT */ uint32_t *binary_len, /* OUT */ const uint8_t **binary) /* OUT */ { bson_subtype_t backup; BSON_ASSERT (iter); BSON_ASSERT (!binary || binary_len); if (ITER_TYPE (iter) == BSON_TYPE_BINARY) { if (!subtype) { subtype = &backup; } *subtype = (bson_subtype_t) * (iter->raw + iter->d2); if (binary) { memcpy (binary_len, (iter->raw + iter->d1), sizeof (*binary_len)); *binary_len = BSON_UINT32_FROM_LE (*binary_len); *binary = iter->raw + iter->d3; if (*subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { *binary_len -= sizeof (int32_t); *binary += sizeof (int32_t); } } return; } if (binary) { *binary = NULL; } if (binary_len) { *binary_len = 0; } if (subtype) { *subtype = BSON_SUBTYPE_BINARY; } } /* *-------------------------------------------------------------------------- * * bson_iter_bool -- * * Retrieves the current field of type BSON_TYPE_BOOL. * * Returns: * true or false, dependent on bson document. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { return bson_iter_bool_unsafe (iter); } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_as_bool -- * * If @iter is on a boolean field, returns the boolean. If it is on a * non-boolean field such as int32, int64, or double, it will convert * the value to a boolean. * * Zero is false, and non-zero is true. * * Returns: * true or false, dependent on field type. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_as_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return !(bson_iter_double (iter) == 0.0); case BSON_TYPE_INT64: return !(bson_iter_int64 (iter) == 0); case BSON_TYPE_INT32: return !(bson_iter_int32 (iter) == 0); case BSON_TYPE_UTF8: return true; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: return false; default: return true; } } /* *-------------------------------------------------------------------------- * * bson_iter_double -- * * Retrieves the current field of type BSON_TYPE_DOUBLE. * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { return bson_iter_double_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_double -- * * If @iter is on a field of type BSON_TYPE_DOUBLE, * returns the double. If it is on an integer field * such as int32, int64, or bool, it will convert * the value to a double. * * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_as_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (double) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return bson_iter_double (iter); case BSON_TYPE_INT32: return (double) bson_iter_int32 (iter); case BSON_TYPE_INT64: return (double) bson_iter_int64 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_int32 -- * * Retrieves the value of the field of type BSON_TYPE_INT32. * * Returns: * A 32-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int32_t bson_iter_int32 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { return bson_iter_int32_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_int64 -- * * Retrieves a 64-bit signed integer for the current BSON_TYPE_INT64 * field. * * Returns: * A 64-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_int64 -- * * If @iter is not an int64 field, it will try to convert the value to * an int64. Such field types include: * * - bool * - double * - int32 * * Returns: * An int64_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_as_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (int64_t) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return (int64_t) bson_iter_double (iter); case BSON_TYPE_INT64: return bson_iter_int64 (iter); case BSON_TYPE_INT32: return (int64_t) bson_iter_int32 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_decimal128 -- * * This function retrieves the current field of type *%BSON_TYPE_DECIMAL128. * The result is valid while @iter is valid, and is stored in @dec. * * Returns: * * True on success, false on failure. * * Side Effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_decimal128 (const bson_iter_t *iter, /* IN */ bson_decimal128_t *dec) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { bson_iter_decimal128_unsafe (iter, dec); return true; } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_oid -- * * Retrieves the current field of type %BSON_TYPE_OID. The result is * valid while @iter is valid. * * Returns: * A bson_oid_t that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_oid_t * bson_iter_oid (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { return bson_iter_oid_unsafe (iter); } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_regex -- * * Fetches the current field from the iter which should be of type * BSON_TYPE_REGEX. * * Returns: * Regex from @iter. This should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_regex (const bson_iter_t *iter, /* IN */ const char **options) /* IN */ { const char *ret = NULL; const char *ret_options = NULL; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_REGEX) { ret = (const char *) (iter->raw + iter->d1); ret_options = (const char *) (iter->raw + iter->d2); } if (options) { *options = ret_options; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_utf8 -- * * Retrieves the current field of type %BSON_TYPE_UTF8 as a UTF-8 * encoded string. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the string. * * Returns: * A string that should not be modified or freed. * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ const char * bson_iter_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_UTF8) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dup_utf8 -- * * Copies the current UTF-8 element into a newly allocated string. The * string should be freed using bson_free() when the caller is * finished with it. * * Returns: * A newly allocated char* that should be freed with bson_free(). * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ char * bson_iter_dup_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { uint32_t local_length = 0; const char *str; char *ret = NULL; BSON_ASSERT (iter); if ((str = bson_iter_utf8 (iter, &local_length))) { ret = bson_malloc0 (local_length + 1); memcpy (ret, str, local_length); ret[local_length] = '\0'; } if (length) { *length = local_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_code -- * * Retrieves the current field of type %BSON_TYPE_CODE. The length of * the resulting string is stored in @length. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the code length. * * Returns: * A NUL-terminated string containing the code which should not be * modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_code (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODE) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_codewscope -- * * Similar to bson_iter_code() but with a scope associated encoded as * a BSON document. @scope should not be modified or freed. It is * valid while @iter is valid. * * Parameters: * @iter: A #bson_iter_t. * @length: A location for the length of resulting string. * @scope_len: A location for the length of @scope. * @scope: A location for the scope encoded as BSON. * * Returns: * A NUL-terminated string that should not be modified or freed. * * Side effects: * @length is set to the resulting string length in bytes. * @scope_len is set to the length of @scope in bytes. * @scope is set to the scope documents buffer which can be * turned into a bson document with bson_init_static(). * *-------------------------------------------------------------------------- */ const char * bson_iter_codewscope (const bson_iter_t *iter, /* IN */ uint32_t *length, /* OUT */ uint32_t *scope_len, /* OUT */ const uint8_t **scope) /* OUT */ { uint32_t len; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) { if (length) { memcpy (&len, iter->raw + iter->d2, sizeof (len)); /* The string length was checked > 0 in _bson_iter_next_internal. */ len = BSON_UINT32_FROM_LE (len); BSON_ASSERT (len > 0); *length = len - 1; } memcpy (&len, iter->raw + iter->d4, sizeof (len)); *scope_len = BSON_UINT32_FROM_LE (len); *scope = iter->raw + iter->d4; return (const char *) (iter->raw + iter->d3); } if (length) { *length = 0; } if (scope_len) { *scope_len = 0; } if (scope) { *scope = NULL; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dbpointer -- * * Retrieves a BSON_TYPE_DBPOINTER field. @collection_len will be set * to the length of the collection name. The collection name will be * placed into @collection. The oid will be placed into @oid. * * @collection and @oid should not be modified. * * Parameters: * @iter: A #bson_iter_t. * @collection_len: A location for the length of @collection. * @collection: A location for the collection name. * @oid: A location for the oid. * * Returns: * None. * * Side effects: * @collection_len is set to the length of @collection in bytes * excluding the null byte. * @collection is set to the collection name, including a terminating * null byte. * @oid is initialized with the oid. * *-------------------------------------------------------------------------- */ void bson_iter_dbpointer (const bson_iter_t *iter, /* IN */ uint32_t *collection_len, /* OUT */ const char **collection, /* OUT */ const bson_oid_t **oid) /* OUT */ { BSON_ASSERT (iter); if (collection) { *collection = NULL; } if (oid) { *oid = NULL; } if (ITER_TYPE (iter) == BSON_TYPE_DBPOINTER) { if (collection_len) { memcpy ( collection_len, (iter->raw + iter->d1), sizeof (*collection_len)); *collection_len = BSON_UINT32_FROM_LE (*collection_len); if ((*collection_len) > 0) { (*collection_len)--; } } if (collection) { *collection = (const char *) (iter->raw + iter->d2); } if (oid) { *oid = (const bson_oid_t *) (iter->raw + iter->d3); } } } /* *-------------------------------------------------------------------------- * * bson_iter_symbol -- * * Retrieves the symbol of the current field of type BSON_TYPE_SYMBOL. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the symbol. * * Returns: * A string containing the symbol as UTF-8. The value should not be * modified or freed. * * Side effects: * @length is set to the resulting strings length in bytes, * excluding the null byte. * *-------------------------------------------------------------------------- */ const char * bson_iter_symbol (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { const char *ret = NULL; uint32_t ret_length = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_SYMBOL) { ret = (const char *) (iter->raw + iter->d2); ret_length = bson_iter_utf8_len_unsafe (iter); } if (length) { *length = ret_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_date_time -- * * Fetches the number of milliseconds elapsed since the UNIX epoch. * This value can be negative as times before 1970 are valid. * * Returns: * A signed 64-bit integer containing the number of milliseconds. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_date_time (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_time_t -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME as a * time_t. * * Returns: * A #time_t of the number of seconds since UNIX epoch in UTC. * * Side effects: * None. * *-------------------------------------------------------------------------- */ time_t bson_iter_time_t (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_time_t_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_timestamp -- * * Fetches the current field if it is a BSON_TYPE_TIMESTAMP. * * Parameters: * @iter: A #bson_iter_t. * @timestamp: a location for the timestamp. * @increment: A location for the increment. * * Returns: * None. * * Side effects: * @timestamp is initialized. * @increment is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timestamp (const bson_iter_t *iter, /* IN */ uint32_t *timestamp, /* OUT */ uint32_t *increment) /* OUT */ { uint64_t encoded; uint32_t ret_timestamp = 0; uint32_t ret_increment = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { memcpy (&encoded, iter->raw + iter->d1, sizeof (encoded)); encoded = BSON_UINT64_FROM_LE (encoded); ret_timestamp = (encoded >> 32) & 0xFFFFFFFF; ret_increment = encoded & 0xFFFFFFFF; } if (timestamp) { *timestamp = ret_timestamp; } if (increment) { *increment = ret_increment; } } /* *-------------------------------------------------------------------------- * * bson_iter_timeval -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME and stores * it into the struct timeval provided. tv->tv_sec is set to the * number of seconds since the UNIX epoch in UTC. * * Since BSON_TYPE_DATE_TIME does not support fractions of a second, * tv->tv_usec will always be set to zero. * * Returns: * None. * * Side effects: * @tv is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timeval (const bson_iter_t *iter, /* IN */ struct timeval *tv) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { bson_iter_timeval_unsafe (iter, tv); return; } memset (tv, 0, sizeof *tv); } /** * bson_iter_document: * @iter: a bson_iter_t. * @document_len: A location for the document length. * @document: A location for a pointer to the document buffer. * */ /* *-------------------------------------------------------------------------- * * bson_iter_document -- * * Retrieves the data to the document BSON structure and stores the * length of the document buffer in @document_len and the document * buffer in @document. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_document(iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the bson_t structure as no data can be * modified in the process of its use (as it is static/const). * * Returns: * None. * * Side effects: * @document_len is initialized. * @document is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_document (const bson_iter_t *iter, /* IN */ uint32_t *document_len, /* OUT */ const uint8_t **document) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (document_len); BSON_ASSERT (document); *document = NULL; *document_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len)); *document_len = BSON_UINT32_FROM_LE (*document_len); *document = (iter->raw + iter->d1); } } /** * bson_iter_array: * @iter: a #bson_iter_t. * @array_len: A location for the array length. * @array: A location for a pointer to the array buffer. */ /* *-------------------------------------------------------------------------- * * bson_iter_array -- * * Retrieves the data to the array BSON structure and stores the * length of the array buffer in @array_len and the array buffer in * @array. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_array (iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the #bson_t structure as no data can be * modified in the process of its use. * * Returns: * None. * * Side effects: * @array_len is initialized. * @array is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_array (const bson_iter_t *iter, /* IN */ uint32_t *array_len, /* OUT */ const uint8_t **array) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (array_len); BSON_ASSERT (array); *array = NULL; *array_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { memcpy (array_len, (iter->raw + iter->d1), sizeof (*array_len)); *array_len = BSON_UINT32_FROM_LE (*array_len); *array = (iter->raw + iter->d1); } } #define VISIT_FIELD(name) visitor->visit_##name && visitor->visit_##name #define VISIT_AFTER VISIT_FIELD (after) #define VISIT_BEFORE VISIT_FIELD (before) #define VISIT_CORRUPT \ if (visitor->visit_corrupt) \ visitor->visit_corrupt #define VISIT_DOUBLE VISIT_FIELD (double) #define VISIT_UTF8 VISIT_FIELD (utf8) #define VISIT_DOCUMENT VISIT_FIELD (document) #define VISIT_ARRAY VISIT_FIELD (array) #define VISIT_BINARY VISIT_FIELD (binary) #define VISIT_UNDEFINED VISIT_FIELD (undefined) #define VISIT_OID VISIT_FIELD (oid) #define VISIT_BOOL VISIT_FIELD (bool) #define VISIT_DATE_TIME VISIT_FIELD (date_time) #define VISIT_NULL VISIT_FIELD (null) #define VISIT_REGEX VISIT_FIELD (regex) #define VISIT_DBPOINTER VISIT_FIELD (dbpointer) #define VISIT_CODE VISIT_FIELD (code) #define VISIT_SYMBOL VISIT_FIELD (symbol) #define VISIT_CODEWSCOPE VISIT_FIELD (codewscope) #define VISIT_INT32 VISIT_FIELD (int32) #define VISIT_TIMESTAMP VISIT_FIELD (timestamp) #define VISIT_INT64 VISIT_FIELD (int64) #define VISIT_DECIMAL128 VISIT_FIELD (decimal128) #define VISIT_MAXKEY VISIT_FIELD (maxkey) #define VISIT_MINKEY VISIT_FIELD (minkey) bool bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ const bson_visitor_t *visitor, /* IN */ void *data) /* IN */ { uint32_t bson_type; const char *key; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (visitor); while (_bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported)) { if (*key && !bson_utf8_validate (key, strlen (key), false)) { iter->err_off = iter->off; break; } if (VISIT_BEFORE (iter, key, data)) { return true; } switch (bson_type) { case BSON_TYPE_DOUBLE: if (VISIT_DOUBLE (iter, key, bson_iter_double (iter), data)) { return true; } break; case BSON_TYPE_UTF8: { uint32_t utf8_len; const char *utf8; utf8 = bson_iter_utf8 (iter, &utf8_len); if (!bson_utf8_validate (utf8, utf8_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_UTF8 (iter, key, utf8_len, utf8, data)) { return true; } } break; case BSON_TYPE_DOCUMENT: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_document (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_DOCUMENT (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_ARRAY: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_array (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_ARRAY (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_BINARY: { const uint8_t *binary = NULL; bson_subtype_t subtype = BSON_SUBTYPE_BINARY; uint32_t binary_len = 0; bson_iter_binary (iter, &subtype, &binary_len, &binary); if (VISIT_BINARY (iter, key, subtype, binary_len, binary, data)) { return true; } } break; case BSON_TYPE_UNDEFINED: if (VISIT_UNDEFINED (iter, key, data)) { return true; } break; case BSON_TYPE_OID: if (VISIT_OID (iter, key, bson_iter_oid (iter), data)) { return true; } break; case BSON_TYPE_BOOL: if (VISIT_BOOL (iter, key, bson_iter_bool (iter), data)) { return true; } break; case BSON_TYPE_DATE_TIME: if (VISIT_DATE_TIME (iter, key, bson_iter_date_time (iter), data)) { return true; } break; case BSON_TYPE_NULL: if (VISIT_NULL (iter, key, data)) { return true; } break; case BSON_TYPE_REGEX: { const char *regex = NULL; const char *options = NULL; regex = bson_iter_regex (iter, &options); if (!bson_utf8_validate (regex, strlen (regex), true)) { iter->err_off = iter->off; return true; } if (VISIT_REGEX (iter, key, regex, options, data)) { return true; } } break; case BSON_TYPE_DBPOINTER: { uint32_t collection_len = 0; const char *collection = NULL; const bson_oid_t *oid = NULL; bson_iter_dbpointer (iter, &collection_len, &collection, &oid); if (!bson_utf8_validate (collection, collection_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_DBPOINTER ( iter, key, collection_len, collection, oid, data)) { return true; } } break; case BSON_TYPE_CODE: { uint32_t code_len; const char *code; code = bson_iter_code (iter, &code_len); if (!bson_utf8_validate (code, code_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_CODE (iter, key, code_len, code, data)) { return true; } } break; case BSON_TYPE_SYMBOL: { uint32_t symbol_len; const char *symbol; symbol = bson_iter_symbol (iter, &symbol_len); if (!bson_utf8_validate (symbol, symbol_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_SYMBOL (iter, key, symbol_len, symbol, data)) { return true; } } break; case BSON_TYPE_CODEWSCOPE: { uint32_t length = 0; const char *code; const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; code = bson_iter_codewscope (iter, &length, &doclen, &docbuf); if (!bson_utf8_validate (code, length, true)) { iter->err_off = iter->off; return true; } if (bson_init_static (&b, docbuf, doclen) && VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { return true; } } break; case BSON_TYPE_INT32: if (VISIT_INT32 (iter, key, bson_iter_int32 (iter), data)) { return true; } break; case BSON_TYPE_TIMESTAMP: { uint32_t timestamp; uint32_t increment; bson_iter_timestamp (iter, &timestamp, &increment); if (VISIT_TIMESTAMP (iter, key, timestamp, increment, data)) { return true; } } break; case BSON_TYPE_INT64: if (VISIT_INT64 (iter, key, bson_iter_int64 (iter), data)) { return true; } break; case BSON_TYPE_DECIMAL128: { bson_decimal128_t dec; bson_iter_decimal128 (iter, &dec); if (VISIT_DECIMAL128 (iter, key, &dec, data)) { return true; } } break; case BSON_TYPE_MAXKEY: if (VISIT_MAXKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_MINKEY: if (VISIT_MINKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_EOD: default: break; } if (VISIT_AFTER (iter, bson_iter_key_unsafe (iter), data)) { return true; } } if (iter->err_off) { if (unsupported && visitor->visit_unsupported_type && bson_utf8_validate (key, strlen (key), false)) { visitor->visit_unsupported_type (iter, key, bson_type, data); return false; } VISIT_CORRUPT (iter, data); } #undef VISIT_FIELD return false; } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_bool -- * * Overwrites the current BSON_TYPE_BOOLEAN field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_bool (bson_iter_t *iter, /* IN */ bool value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { memcpy ((void *) (iter->raw + iter->d1), &value, 1); } } void bson_iter_overwrite_oid (bson_iter_t *iter, const bson_oid_t *value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { memcpy ( (void *) (iter->raw + iter->d1), value->bytes, sizeof (value->bytes)); } } void bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment) { uint64_t value; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { value = ((((uint64_t) timestamp) << 32U) | ((uint64_t) increment)); value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } void bson_iter_overwrite_date_time (bson_iter_t *iter, int64_t value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int32 -- * * Overwrites the current BSON_TYPE_INT32 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int32 (bson_iter_t *iter, /* IN */ int32_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT32_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int64 -- * * Overwrites the current BSON_TYPE_INT64 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int64 (bson_iter_t *iter, /* IN */ int64_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT64_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_double -- * * Overwrites the current BSON_TYPE_DOUBLE field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_double (bson_iter_t *iter, /* IN */ double value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { value = BSON_DOUBLE_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_decimal128 -- * * Overwrites the current BSON_TYPE_DECIMAL128 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_decimal128 (bson_iter_t *iter, /* IN */ bson_decimal128_t *value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN uint64_t data[2]; data[0] = BSON_UINT64_TO_LE (value->low); data[1] = BSON_UINT64_TO_LE (value->high); memcpy ((void *) (iter->raw + iter->d1), data, sizeof (data)); #else memcpy ((void *) (iter->raw + iter->d1), value, sizeof (*value)); #endif } } /* *-------------------------------------------------------------------------- * * bson_iter_value -- * * Retrieves a bson_value_t containing the boxed value of the current * element. The result of this function valid until the state of * iter has been changed (through the use of bson_iter_next()). * * Returns: * A bson_value_t that should not be modified or freed. If you need * to hold on to the value, use bson_value_copy(). * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_value_t * bson_iter_value (bson_iter_t *iter) /* IN */ { bson_value_t *value; BSON_ASSERT (iter); value = &iter->value; value->value_type = ITER_TYPE (iter); switch (value->value_type) { case BSON_TYPE_DOUBLE: value->value.v_double = bson_iter_double (iter); break; case BSON_TYPE_UTF8: value->value.v_utf8.str = (char *) bson_iter_utf8 (iter, &value->value.v_utf8.len); break; case BSON_TYPE_DOCUMENT: bson_iter_document (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_ARRAY: bson_iter_array (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_BINARY: bson_iter_binary (iter, &value->value.v_binary.subtype, &value->value.v_binary.data_len, (const uint8_t **) &value->value.v_binary.data); break; case BSON_TYPE_OID: bson_oid_copy (bson_iter_oid (iter), &value->value.v_oid); break; case BSON_TYPE_BOOL: value->value.v_bool = bson_iter_bool (iter); break; case BSON_TYPE_DATE_TIME: value->value.v_datetime = bson_iter_date_time (iter); break; case BSON_TYPE_REGEX: value->value.v_regex.regex = (char *) bson_iter_regex ( iter, (const char **) &value->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: { const bson_oid_t *oid; bson_iter_dbpointer (iter, &value->value.v_dbpointer.collection_len, (const char **) &value->value.v_dbpointer.collection, &oid); bson_oid_copy (oid, &value->value.v_dbpointer.oid); break; } case BSON_TYPE_CODE: value->value.v_code.code = (char *) bson_iter_code (iter, &value->value.v_code.code_len); break; case BSON_TYPE_SYMBOL: value->value.v_symbol.symbol = (char *) bson_iter_symbol (iter, &value->value.v_symbol.len); break; case BSON_TYPE_CODEWSCOPE: value->value.v_codewscope.code = (char *) bson_iter_codewscope ( iter, &value->value.v_codewscope.code_len, &value->value.v_codewscope.scope_len, (const uint8_t **) &value->value.v_codewscope.scope_data); break; case BSON_TYPE_INT32: value->value.v_int32 = bson_iter_int32 (iter); break; case BSON_TYPE_TIMESTAMP: bson_iter_timestamp (iter, &value->value.v_timestamp.timestamp, &value->value.v_timestamp.increment); break; case BSON_TYPE_INT64: value->value.v_int64 = bson_iter_int64 (iter); break; case BSON_TYPE_DECIMAL128: bson_iter_decimal128 (iter, &(value->value.v_decimal128)); break; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: break; case BSON_TYPE_EOD: default: return NULL; } return value; } uint32_t bson_iter_key_len (const bson_iter_t *iter) { /* * f i e l d n a m e \0 _ * ^ ^ * | | * iter->key iter->d1 * */ BSON_ASSERT (iter->d1 > iter->key); return iter->d1 - iter->key - 1; } bool bson_iter_init_from_data_at_offset (bson_iter_t *iter, const uint8_t *data, size_t length, uint32_t offset, uint32_t keylen) { const char *key; uint32_t bson_type; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = (uint32_t) length; iter->off = 0; iter->type = 0; iter->key = 0; iter->next_off = offset; iter->err_off = 0; if (!_bson_iter_next_internal ( iter, keylen, &key, &bson_type, &unsupported)) { memset (iter, 0, sizeof *iter); return false; } return true; } uint32_t bson_iter_offset (bson_iter_t *iter) { return iter->off; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_372_0
crossvul-cpp_data_bad_5301_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M EEEEE TTTTT AAA % % MM MM E T A A % % M M M EEE T AAAAA % % M M E T A A % % M M EEEEE T A A % % % % % % Read/Write Embedded Image Profiles. % % % % Software Design % % William Radcliffe % % July 2001 % % % % % % 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/blob.h" #include "magick/blob-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/pixel-accessor.h" #include "magick/profile.h" #include "magick/quantum-private.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/token.h" #include "magick/utility.h" /* Forward declarations. */ static MagickBooleanType WriteMETAImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M E T A % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMETA() returns MagickTrue if the image format type, identified by the % magick string, is META. % % The format of the IsMETA method is: % % MagickBooleanType IsMETA(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. % % */ #ifdef IMPLEMENT_IS_FUNCTION static MagickBooleanType IsMETA(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"8BIM",4) == 0) return(MagickTrue); if (LocaleNCompare((char *) magick,"APP1",4) == 0) return(MagickTrue); if (LocaleNCompare((char *) magick,"\034\002",2) == 0) return(MagickTrue); return(MagickFalse); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMETAImage() reads a META 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 ReadMETAImage method is: % % Image *ReadMETAImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image: Method ReadMETAImage 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 an ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ typedef struct _html_code { const short len; const char *code, val; } html_code; static const html_code html_codes[] = { #ifdef HANDLE_GT_LT { 4,"&lt;",'<' }, { 4,"&gt;",'>' }, #endif { 5,"&amp;",'&' }, { 6,"&quot;",'"' }, { 6,"&apos;",'\''} }; static int stringnicmp(const char *p,const char *q,size_t n) { register ssize_t i, j; if (p == q) return(0); if (p == (char *) NULL) return(-1); if (q == (char *) NULL) return(1); while ((*p != '\0') && (*q != '\0')) { if ((*p == '\0') || (*q == '\0')) break; i=(*p); if (islower(i)) i=toupper(i); j=(*q); if (islower(j)) j=toupper(j); if (i != j) break; n--; if (n == 0) break; p++; q++; } return(toupper((int) *p)-toupper((int) *q)); } static int convertHTMLcodes(char *s, int len) { if (len <=0 || s==(char*) NULL || *s=='\0') return 0; if (s[1] == '#') { int val, o; if (sscanf(s,"&#%d;",&val) == 1) { o = 3; while (s[o] != ';') { o++; if (o > 5) break; } if (o < 6) (void) memmove(s+1,s+1+o,strlen(s+1+o)+1); *s = val; return o; } } else { int i, codes = (int) (sizeof(html_codes) / sizeof(html_code)); for (i=0; i < codes; i++) { if (html_codes[i].len <= len) if (stringnicmp(s,html_codes[i].code,(size_t) html_codes[i].len) == 0) { (void) memmove(s+1,s+html_codes[i].len, strlen(s+html_codes[i].len)+1); *s = html_codes[i].val; return html_codes[i].len-1; } } } return 0; } static char *super_fgets(char **b, int *blen, Image *file) { int c, len; unsigned char *p, *q; len=*blen; p=(unsigned char *) (*b); for (q=p; ; q++) { c=ReadBlobByte(file); if (c == EOF || c == '\n') break; if ((q-p+1) >= (int) len) { int tlen; tlen=q-p; len<<=1; p=(unsigned char *) ResizeQuantumMemory(p,(size_t) len+2UL,sizeof(*p)); *b=(char *) p; if (p == (unsigned char *) NULL) break; q=p+tlen; } *q=(unsigned char) c; } *blen=0; if (p != (unsigned char *) NULL) { int tlen; tlen=q-p; if (tlen == 0) return (char *) NULL; p[tlen] = '\0'; *blen=++tlen; } return((char *) p); } #define IPTC_ID 1028 #define THUMBNAIL_ID 1033 static ssize_t parse8BIM(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MaxTextExtent; MagickOffsetType savedpos, currentpos; ssize_t savedolen = 0L, outputlen = 0L; TokenInfo *token_info; dataset = 0; recnum = 0; line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets(&line,&inputlen,ifile)!=NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0, &brkused,&next,&quoted)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#", "", 0,&brkused,&next,&quoted)==0) { switch (state) { case 0: if (strcmp(newstr,"8BIM")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum = (unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MaxTextExtent, sizeof(*name)); if (name) (void) strcpy(name,newstr); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&", "",0,&brkused,&next,&quoted)==0) { if (brkused && next > 0) { char *s = &token[next-1]; len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s)); } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,"8BIM"); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,nlen); outputlen++; for (i=0; i<nlen; i++) (void) WriteBlobByte(ofile,(unsigned char) name[i]); outputlen += nlen; if ((nlen & 0x01) == 0) { (void) WriteBlobByte(ofile,0x00); outputlen++; } if (recnum != IPTC_ID) { (void) WriteBlobMSBLong(ofile, (unsigned int) len); outputlen += 4; next=0; outputlen += len; while (len--) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } } else { /* patch in a fake length for now and fix it later */ savedpos = TellBlob(ofile); if (savedpos < 0) return(-1); (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU); outputlen += 4; savedolen = outputlen; } } else { if (len <= 0x7FFF) { (void) WriteBlobByte(ofile,0x1c); (void) WriteBlobByte(ofile,(unsigned char) dataset); (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff)); (void) WriteBlobMSBShort(ofile,(unsigned short) len); outputlen += 5; next=0; outputlen += len; while (len--) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); } } } state++; } if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); } token_info=DestroyTokenInfo(token_info); if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); line=DestroyString(line); if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return(outputlen); } static char *super_fgets_w(char **b, int *blen, Image *file) { int c, len; unsigned char *p, *q; len=*blen; p=(unsigned char *) (*b); for (q=p; ; q++) { c=(int) ReadBlobLSBShort(file); if ((c == -1) || (c == '\n')) break; if (EOFBlob(file)) break; if ((q-p+1) >= (int) len) { int tlen; tlen=q-p; len<<=1; p=(unsigned char *) ResizeQuantumMemory(p,(size_t) (len+2),sizeof(*p)); *b=(char *) p; if (p == (unsigned char *) NULL) break; q=p+tlen; } *q=(unsigned char) c; } *blen=0; if ((*b) != (char *) NULL) { int tlen; tlen=q-p; if (tlen == 0) return (char *) NULL; p[tlen] = '\0'; *blen=++tlen; } return((char *) p); } static ssize_t parse8BIMW(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MaxTextExtent; ssize_t savedolen = 0L, outputlen = 0L; MagickOffsetType savedpos, currentpos; TokenInfo *token_info; dataset = 0; recnum = 0; line=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets_w(&line,&inputlen,ifile) != NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0, &brkused,&next,&quoted)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#", "",0,&brkused,&next,&quoted)==0) { switch (state) { case 0: if (strcmp(newstr,"8BIM")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum=(unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MaxTextExtent, sizeof(*name)); if (name) (void) CopyMagickString(name,newstr,strlen(newstr)+MaxTextExtent); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&", "",0,&brkused,&next,&quoted)==0) { if (brkused && next > 0) { char *s = &token[next-1]; len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s)); } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,"8BIM"); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,(unsigned char) nlen); outputlen++; for (i=0; i<nlen; i++) (void) WriteBlobByte(ofile,(unsigned char) name[i]); outputlen += nlen; if ((nlen & 0x01) == 0) { (void) WriteBlobByte(ofile,0x00); outputlen++; } if (recnum != IPTC_ID) { (void) WriteBlobMSBLong(ofile,(unsigned int) len); outputlen += 4; next=0; outputlen += len; while (len--) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } } else { /* patch in a fake length for now and fix it later */ savedpos = TellBlob(ofile); if (savedpos < 0) return(-1); (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU); outputlen += 4; savedolen = outputlen; } } else { if (len <= 0x7FFF) { (void) WriteBlobByte(ofile,0x1c); (void) WriteBlobByte(ofile,dataset); (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff)); (void) WriteBlobMSBShort(ofile,(unsigned short) len); outputlen += 5; next=0; outputlen += len; while (len--) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); } } } state++; } if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); } token_info=DestroyTokenInfo(token_info); if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); line=DestroyString(line); if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return outputlen; } /* some defines for the different JPEG block types */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xe0 #define M_APP1 0xe1 #define M_APP2 0xe2 #define M_APP3 0xe3 #define M_APP4 0xe4 #define M_APP5 0xe5 #define M_APP6 0xe6 #define M_APP7 0xe7 #define M_APP8 0xe8 #define M_APP9 0xe9 #define M_APP10 0xea #define M_APP11 0xeb #define M_APP12 0xec #define M_APP13 0xed #define M_APP14 0xee #define M_APP15 0xef static int jpeg_transfer_1(Image *ifile, Image *ofile) { int c; c = ReadBlobByte(ifile); if (c == EOF) return EOF; (void) WriteBlobByte(ofile,(unsigned char) c); return c; } #if defined(future) static int jpeg_skip_1(Image *ifile) { int c; c = ReadBlobByte(ifile); if (c == EOF) return EOF; return c; } #endif static int jpeg_read_remaining(Image *ifile, Image *ofile) { int c; while ((c = jpeg_transfer_1(ifile, ofile)) != EOF) continue; return M_EOI; } static int jpeg_skip_variable(Image *ifile, Image *ofile) { unsigned int length; int c1,c2; if ((c1 = jpeg_transfer_1(ifile, ofile)) == EOF) return M_EOI; if ((c2 = jpeg_transfer_1(ifile, ofile)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) if (jpeg_transfer_1(ifile, ofile) == EOF) return M_EOI; return 0; } static int jpeg_skip_variable2(Image *ifile, Image *ofile) { unsigned int length; int c1,c2; (void) ofile; if ((c1 = ReadBlobByte(ifile)) == EOF) return M_EOI; if ((c2 = ReadBlobByte(ifile)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) if (ReadBlobByte(ifile) == EOF) return M_EOI; return 0; } static int jpeg_nextmarker(Image *ifile, Image *ofile) { int c; /* transfer anything until we hit 0xff */ do { c = ReadBlobByte(ifile); if (c == EOF) return M_EOI; /* we hit EOF */ else if (c != 0xff) (void) WriteBlobByte(ofile,(unsigned char) c); } while (c != 0xff); /* get marker byte, swallowing possible padding */ do { c = ReadBlobByte(ifile); if (c == EOF) return M_EOI; /* we hit EOF */ } while (c == 0xff); return c; } #if defined(future) static int jpeg_skip_till_marker(Image *ifile, int marker) { int c, i; do { /* skip anything until we hit 0xff */ i = 0; do { c = ReadBlobByte(ifile); i++; if (c == EOF) return M_EOI; /* we hit EOF */ } while (c != 0xff); /* get marker byte, swallowing possible padding */ do { c = ReadBlobByte(ifile); if (c == EOF) return M_EOI; /* we hit EOF */ } while (c == 0xff); } while (c != marker); return c; } #endif /* Embed binary IPTC data into a JPEG image. */ static int jpeg_embed(Image *ifile, Image *ofile, Image *iptc) { unsigned int marker; unsigned int done = 0; unsigned int len; int inx; if (jpeg_transfer_1(ifile, ofile) != 0xFF) return 0; if (jpeg_transfer_1(ifile, ofile) != M_SOI) return 0; while (done == MagickFalse) { marker=(unsigned int) jpeg_nextmarker(ifile, ofile); if (marker == M_EOI) { /* EOF */ break; } else { if (marker != M_APP13) { (void) WriteBlobByte(ofile,0xff); (void) WriteBlobByte(ofile,(unsigned char) marker); } } switch (marker) { case M_APP13: /* we are going to write a new APP13 marker, so don't output the old one */ jpeg_skip_variable2(ifile, ofile); break; case M_APP0: /* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */ jpeg_skip_variable(ifile, ofile); if (iptc != (Image *) NULL) { char psheader[] = "\xFF\xED\0\0Photoshop 3.0\0" "8BIM\x04\x04\0\0\0\0"; len=(unsigned int) GetBlobSize(iptc); if (len & 1) len++; /* make the length even */ psheader[2]=(char) ((len+16)>>8); psheader[3]=(char) ((len+16)&0xff); for (inx = 0; inx < 18; inx++) (void) WriteBlobByte(ofile,(unsigned char) psheader[inx]); jpeg_read_remaining(iptc, ofile); len=(unsigned int) GetBlobSize(iptc); if (len & 1) (void) WriteBlobByte(ofile,0); } break; case M_SOS: /* we hit data, no more marker-inserting can be done! */ jpeg_read_remaining(ifile, ofile); done = 1; break; default: jpeg_skip_variable(ifile, ofile); break; } } return 1; } /* handle stripping the APP13 data out of a JPEG */ #if defined(future) static void jpeg_strip(Image *ifile, Image *ofile) { unsigned int marker; marker = jpeg_skip_till_marker(ifile, M_SOI); if (marker == M_SOI) { (void) WriteBlobByte(ofile,0xff); (void) WriteBlobByte(ofile,M_SOI); jpeg_read_remaining(ifile, ofile); } } /* Extract any APP13 binary data into a file. */ static int jpeg_extract(Image *ifile, Image *ofile) { unsigned int marker; unsigned int done = 0; if (jpeg_skip_1(ifile) != 0xff) return 0; if (jpeg_skip_1(ifile) != M_SOI) return 0; while (done == MagickFalse) { marker = jpeg_skip_till_marker(ifile, M_APP13); if (marker == M_APP13) { marker = jpeg_nextmarker(ifile, ofile); break; } } return 1; } #endif static void CopyBlob(Image *source,Image *destination) { ssize_t i; unsigned char *buffer; ssize_t count, length; buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent, sizeof(*buffer)); if (buffer != (unsigned char *) NULL) { i=0; while ((length=ReadBlob(source,MagickMaxBufferExtent,buffer)) != 0) { count=0; for (i=0; i < (ssize_t) length; i+=count) { count=WriteBlob(destination,(size_t) (length-i),buffer+i); if (count <= 0) break; } if (i < (ssize_t) length) break; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); } } static Image *ReadMETAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *buff, *image; MagickBooleanType status; StringInfo *profile; size_t length; void *blob; /* Open file containing binary metadata */ 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); } image->columns=1; image->rows=1; if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } length=1; if (LocaleNCompare(image_info->magick,"8BIM",4) == 0) { /* Read 8BIM binary metadata. */ buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0) { length=(size_t) parse8BIM(image, buff); if (length & 1) (void) WriteBlobByte(buff,0x0); } else if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0) { length=(size_t) parse8BIMW(image, buff); if (length & 1) (void) WriteBlobByte(buff,0x0); } else CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if (LocaleNCompare(image_info->magick,"APP1",4) == 0) { char name[MaxTextExtent]; (void) FormatLocaleString(name,MaxTextExtent,"APP%d",1); buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); if (LocaleCompare(image_info->magick,"APP1JPEG") == 0) { Image *iptc; int result; if (image_info->profile == (void *) NULL) { blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); ThrowReaderException(CoderError,"NoIPTCProfileAvailable"); } profile=CloneStringInfo((StringInfo *) image_info->profile); iptc=AcquireImage((ImageInfo *) NULL); if (iptc == (Image *) NULL) { blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(iptc->blob,GetStringInfoDatum(profile), GetStringInfoLength(profile)); result=jpeg_embed(image,buff,iptc); blob=DetachBlob(iptc->blob); blob=RelinquishMagickMemory(blob); iptc=DestroyImage(iptc); if (result == 0) { blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); ThrowReaderException(CoderError,"JPEGEmbeddingFailed"); } } else CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=SetImageProfile(image,name,profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=DetachBlob(buff->blob); blob=RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if ((LocaleCompare(image_info->magick,"ICC") == 0) || (LocaleCompare(image_info->magick,"ICM") == 0)) { buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if (LocaleCompare(image_info->magick,"IPTC") == 0) { buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProfile(image,"iptc",profile); profile=DestroyStringInfo(profile); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } if (LocaleCompare(image_info->magick,"XMP") == 0) { buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char)); if (blob == (unsigned char *) NULL) { buff=DestroyImage(buff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } AttachBlob(buff->blob,blob,length); CopyBlob(image,buff); profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t) GetBlobSize(buff)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProfile(image,"xmp",profile); profile=DestroyStringInfo(profile); blob=DetachBlob(buff->blob); blob=(unsigned char *) RelinquishMagickMemory(blob); buff=DestroyImage(buff); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMETAImage() adds attributes for the META 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 RegisterMETAImage method is: % % size_t RegisterMETAImage(void) % */ ModuleExport size_t RegisterMETAImage(void) { MagickInfo *entry; entry=SetMagickInfo("8BIM"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Photoshop resource format"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("8BIMTEXT"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Photoshop resource text format"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("8BIMWTEXT"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Photoshop resource wide text format"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("APP1"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw application information"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("APP1JPEG"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw JPEG binary data"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EXIF"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Exif digital camera binary data"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("XMP"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe XML metadata"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("ICM"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("ICC Color Profile"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("ICC"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("ICC Color Profile"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("IPTC"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("IPTC Newsphoto"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("IPTCTEXT"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("IPTC Newsphoto text format"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("IPTCWTEXT"); entry->decoder=(DecodeImageHandler *) ReadMETAImage; entry->encoder=(EncodeImageHandler *) WriteMETAImage; entry->adjoin=MagickFalse; entry->stealth=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("IPTC Newsphoto text format"); entry->module=ConstantString("META"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMETAImage() removes format registrations made by the % META module from the list of supported formats. % % The format of the UnregisterMETAImage method is: % % UnregisterMETAImage(void) % */ ModuleExport void UnregisterMETAImage(void) { (void) UnregisterMagickInfo("8BIM"); (void) UnregisterMagickInfo("8BIMTEXT"); (void) UnregisterMagickInfo("8BIMWTEXT"); (void) UnregisterMagickInfo("EXIF"); (void) UnregisterMagickInfo("APP1"); (void) UnregisterMagickInfo("APP1JPEG"); (void) UnregisterMagickInfo("ICCTEXT"); (void) UnregisterMagickInfo("ICM"); (void) UnregisterMagickInfo("ICC"); (void) UnregisterMagickInfo("IPTC"); (void) UnregisterMagickInfo("IPTCTEXT"); (void) UnregisterMagickInfo("IPTCWTEXT"); (void) UnregisterMagickInfo("XMP"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M E T A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMETAImage() writes a META image to a file. % % The format of the WriteMETAImage method is: % % MagickBooleanType WriteMETAImage(const ImageInfo *image_info, % Image *image) % % Compression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: Specifies a pointer to an ImageInfo structure. % % o image: A pointer to a Image structure. % */ static size_t GetIPTCStream(unsigned char **info,size_t length) { int c; register ssize_t i; register unsigned char *p; size_t extent, info_length; unsigned int marker; size_t tag_length; p=(*info); extent=length; if ((*p == 0x1c) && (*(p+1) == 0x02)) return(length); /* Extract IPTC from 8BIM resource block. */ while (extent >= 12) { if (strncmp((const char *) p,"8BIM",4)) break; p+=4; extent-=4; marker=(unsigned int) (*p) << 8 | *(p+1); p+=2; extent-=2; c=*p++; extent--; c|=0x01; if ((size_t) c >= extent) break; p+=c; extent-=c; if (extent < 4) break; tag_length=(((size_t) *p) << 24) | (((size_t) *(p+1)) << 16) | (((size_t) *(p+2)) << 8) | ((size_t) *(p+3)); p+=4; extent-=4; if (tag_length > extent) break; if (marker == IPTC_ID) { *info=p; return(tag_length); } if ((tag_length & 0x01) != 0) tag_length++; p+=tag_length; extent-=tag_length; } /* Find the beginning of the IPTC info. */ p=(*info); tag_length=0; iptc_find: info_length=0; marker=MagickFalse; while (length != 0) { c=(*p++); length--; if (length == 0) break; if (c == 0x1c) { p--; *info=p; /* let the caller know were it is */ break; } } /* Determine the length of the IPTC info. */ while (length != 0) { c=(*p++); length--; if (length == 0) break; if (c == 0x1c) marker=MagickTrue; else if (marker) break; else continue; info_length++; /* Found the 0x1c tag; skip the dataset and record number tags. */ c=(*p++); /* should be 2 */ length--; if (length == 0) break; if ((info_length == 1) && (c != 2)) goto iptc_find; info_length++; c=(*p++); /* should be 0 */ length--; if (length == 0) break; if ((info_length == 2) && (c != 0)) goto iptc_find; info_length++; /* Decode the length of the block that follows - ssize_t or short format. */ c=(*p++); length--; if (length == 0) break; info_length++; if ((c & 0x80) != 0) { /* Long format. */ tag_length=0; for (i=0; i < 4; i++) { tag_length<<=8; tag_length|=(*p++); length--; if (length == 0) break; info_length++; } } else { /* Short format. */ tag_length=((long) c) << 8; c=(*p++); length--; if (length == 0) break; info_length++; tag_length|=(long) c; } if (tag_length > (length+1)) break; p+=tag_length; length-=tag_length; if (length == 0) break; info_length+=tag_length; } return(info_length); } static void formatString(Image *ofile, const char *s, int len) { char temp[MaxTextExtent]; (void) WriteBlobByte(ofile,'"'); for (; len > 0; len--, s++) { int c = (*s) & 255; switch (c) { case '&': (void) WriteBlobString(ofile,"&amp;"); break; #ifdef HANDLE_GT_LT case '<': (void) WriteBlobString(ofile,"&lt;"); break; case '>': (void) WriteBlobString(ofile,"&gt;"); break; #endif case '"': (void) WriteBlobString(ofile,"&quot;"); break; default: if (isprint(c)) (void) WriteBlobByte(ofile,(unsigned char) *s); else { (void) FormatLocaleString(temp,MaxTextExtent,"&#%d;", c & 255); (void) WriteBlobString(ofile,temp); } break; } } #if defined(MAGICKCORE_WINDOWS_SUPPORT) (void) WriteBlobString(ofile,"\"\r\n"); #else #if defined(macintosh) (void) WriteBlobString(ofile,"\"\r"); #else (void) WriteBlobString(ofile,"\"\n"); #endif #endif } typedef struct _tag_spec { const short id; const char *name; } tag_spec; static const tag_spec tags[] = { { 5, "Image Name" }, { 7, "Edit Status" }, { 10, "Priority" }, { 15, "Category" }, { 20, "Supplemental Category" }, { 22, "Fixture Identifier" }, { 25, "Keyword" }, { 30, "Release Date" }, { 35, "Release Time" }, { 40, "Special Instructions" }, { 45, "Reference Service" }, { 47, "Reference Date" }, { 50, "Reference Number" }, { 55, "Created Date" }, { 60, "Created Time" }, { 65, "Originating Program" }, { 70, "Program Version" }, { 75, "Object Cycle" }, { 80, "Byline" }, { 85, "Byline Title" }, { 90, "City" }, { 92, "Sub-Location" }, { 95, "Province State" }, { 100, "Country Code" }, { 101, "Country" }, { 103, "Original Transmission Reference" }, { 105, "Headline" }, { 110, "Credit" }, { 115, "Source" }, { 116, "Copyright String" }, { 120, "Caption" }, { 121, "Image Orientation" }, { 122, "Caption Writer" }, { 131, "Local Caption" }, { 200, "Custom Field 1" }, { 201, "Custom Field 2" }, { 202, "Custom Field 3" }, { 203, "Custom Field 4" }, { 204, "Custom Field 5" }, { 205, "Custom Field 6" }, { 206, "Custom Field 7" }, { 207, "Custom Field 8" }, { 208, "Custom Field 9" }, { 209, "Custom Field 10" }, { 210, "Custom Field 11" }, { 211, "Custom Field 12" }, { 212, "Custom Field 13" }, { 213, "Custom Field 14" }, { 214, "Custom Field 15" }, { 215, "Custom Field 16" }, { 216, "Custom Field 17" }, { 217, "Custom Field 18" }, { 218, "Custom Field 19" }, { 219, "Custom Field 20" } }; static int formatIPTC(Image *ifile, Image *ofile) { char temp[MaxTextExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ c = ReadBlobByte(ifile); while (c != EOF) { if (c == 0x1c) foundiptc=1; else { if (foundiptc) return(-1); else { c=0; continue; } } /* we found the 0x1c tag and now grab the dataset and record number tags */ c = ReadBlobByte(ifile); if (c == EOF) return -1; dataset = (unsigned char) c; c = ReadBlobByte(ifile); if (c == EOF) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) { if (tags[i].id == (short) recnum) break; } if (i < tagcount) readable = (unsigned char *) tags[i].name; else readable = (unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=ReadBlobByte(ifile); if (c == EOF) return -1; if (c & (unsigned char) 0x80) return 0; else { int c0; c0=ReadBlobByte(ifile); if (c0 == EOF) return -1; taglen = (c << 8) | c0; } if (taglen < 0) return -1; /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent), sizeof(*str)); if (str == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (tagindx=0; tagindx<taglen; tagindx++) { c=ReadBlobByte(ifile); if (c == EOF) return -1; str[tagindx] = (unsigned char) c; } str[taglen] = 0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d#%s=", (unsigned int) dataset, (unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; c=ReadBlobByte(ifile); } return((int) tagsfound); } static int readWordFromBuffer(char **s, ssize_t *len) { unsigned char buffer[2]; int i, c; for (i=0; i<2; i++) { c = *(*s)++; (*len)--; if (*len < 0) return -1; buffer[i] = (unsigned char) c; } return (((int) buffer[ 0 ]) << 8) | (((int) buffer[ 1 ])); } static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len) { char temp[MaxTextExtent]; unsigned int foundiptc, tagsfound; unsigned char recnum, dataset; unsigned char *readable, *str; ssize_t tagindx, taglen; int i, tagcount = (int) (sizeof(tags) / sizeof(tag_spec)); int c; foundiptc = 0; /* found the IPTC-Header */ tagsfound = 0; /* number of tags found */ while (len > 0) { c = *s++; len--; if (c == 0x1c) foundiptc = 1; else { if (foundiptc) return -1; else continue; } /* We found the 0x1c tag and now grab the dataset and record number tags. */ c = *s++; len--; if (len < 0) return -1; dataset = (unsigned char) c; c = *s++; len--; if (len < 0) return -1; recnum = (unsigned char) c; /* try to match this record to one of the ones in our named table */ for (i=0; i< tagcount; i++) if (tags[i].id == (short) recnum) break; if (i < tagcount) readable=(unsigned char *) tags[i].name; else readable=(unsigned char *) ""; /* We decode the length of the block that follows - ssize_t or short fmt. */ c=(*s++); len--; if (len < 0) return(-1); if (c & (unsigned char) 0x80) return(0); else { s--; len++; taglen=readWordFromBuffer(&s, &len); } if (taglen < 0) return(-1); if (taglen > 65535) return(-1); /* make a buffer to hold the tag datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent), sizeof(*str)); if (str == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (tagindx=0; tagindx<taglen; tagindx++) { c = *s++; len--; if (len < 0) return(-1); str[tagindx]=(unsigned char) c; } str[taglen]=0; /* now finish up by formatting this binary data into ASCII equivalent */ if (strlen((char *)readable) > 0) (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d#%s=", (unsigned int) dataset,(unsigned int) recnum, readable); else (void) FormatLocaleString(temp,MaxTextExtent,"%d#%d=", (unsigned int) dataset,(unsigned int) recnum); (void) WriteBlobString(ofile,temp); formatString( ofile, (char *)str, taglen ); str=(unsigned char *) RelinquishMagickMemory(str); tagsfound++; } return ((int) tagsfound); } static int format8BIM(Image *ifile, Image *ofile) { char temp[MaxTextExtent]; unsigned int foundOSType; int ID, resCount, i, c; ssize_t count; unsigned char *PString, *str; resCount=0; foundOSType=0; /* found the OSType */ (void) foundOSType; c=ReadBlobByte(ifile); while (c != EOF) { if (c == '8') { unsigned char buffer[5]; buffer[0]=(unsigned char) c; for (i=1; i<4; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); buffer[i] = (unsigned char) c; } buffer[4]=0; if (strcmp((const char *)buffer, "8BIM") == 0) foundOSType=1; else continue; } else { c=ReadBlobByte(ifile); continue; } /* We found the OSType (8BIM) and now grab the ID, PString, and Size fields. */ ID=(int) ReadBlobMSBShort(ifile); if (ID < 0) return(-1); { unsigned char plen; c=ReadBlobByte(ifile); if (c == EOF) return(-1); plen = (unsigned char) c; PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+ MaxTextExtent),sizeof(*PString)); if (PString == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (i=0; i<plen; i++) { c=ReadBlobByte(ifile); if (c == EOF) return -1; PString[i] = (unsigned char) c; } PString[ plen ] = 0; if ((plen & 0x01) == 0) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); } } count = (int) ReadBlobMSBLong(ifile); if (count < 0) return -1; /* make a buffer to hold the datand snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str)); if (str == (unsigned char *) NULL) { printf("MemoryAllocationFailed"); return 0; } for (i=0; i < (ssize_t) count; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); str[i]=(unsigned char) c; } /* we currently skip thumbnails, since it does not make * any sense preserving them in a real world application */ if (ID != THUMBNAIL_ID) { /* now finish up by formatting this binary data into * ASCII equivalent */ if (strlen((const char *)PString) > 0) (void) FormatLocaleString(temp,MaxTextExtent,"8BIM#%d#%s=",ID, PString); else (void) FormatLocaleString(temp,MaxTextExtent,"8BIM#%d=",ID); (void) WriteBlobString(ofile,temp); if (ID == IPTC_ID) { formatString(ofile, "IPTC", 4); formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count); } else formatString(ofile, (char *)str, (ssize_t) count); } str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); resCount++; c=ReadBlobByte(ifile); } return resCount; } static MagickBooleanType WriteMETAImage(const ImageInfo *image_info, Image *image) { const StringInfo *profile; MagickBooleanType status; size_t length; /* Open 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); length=0; if (LocaleCompare(image_info->magick,"8BIM") == 0) { /* Write 8BIM image. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"iptc") == 0) { size_t length; unsigned char *info; profile=GetImageProfile(image,"iptc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); info=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); length=GetIPTCStream(&info,length); if (length == 0) ThrowWriterException(CoderError,"NoIPTCProfileAvailable"); (void) WriteBlob(image,length,info); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0) { Image *buff; profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); AttachBlob(buff->blob,GetStringInfoDatum(profile), GetStringInfoLength(profile)); format8BIM(buff,image); (void) DetachBlob(buff->blob); buff=DestroyImage(buff); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0) return(MagickFalse); if (LocaleCompare(image_info->magick,"IPTCTEXT") == 0) { Image *buff; unsigned char *info; profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"No8BIMDataIsAvailable"); info=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); length=GetIPTCStream(&info,length); if (length == 0) ThrowWriterException(CoderError,"NoIPTCProfileAvailable"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); buff=AcquireImage((ImageInfo *) NULL); if (buff == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); AttachBlob(buff->blob,info,length); formatIPTC(buff,image); (void) DetachBlob(buff->blob); buff=DestroyImage(buff); (void) CloseBlob(image); return(MagickTrue); } if (LocaleCompare(image_info->magick,"IPTCWTEXT") == 0) return(MagickFalse); if ((LocaleCompare(image_info->magick,"APP1") == 0) || (LocaleCompare(image_info->magick,"EXIF") == 0) || (LocaleCompare(image_info->magick,"XMP") == 0)) { /* (void) Write APP1 image. */ profile=GetImageProfile(image,image_info->magick); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"NoAPP1DataIsAvailable"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) CloseBlob(image); return(MagickTrue); } if ((LocaleCompare(image_info->magick,"ICC") == 0) || (LocaleCompare(image_info->magick,"ICM") == 0)) { /* Write ICM image. */ profile=GetImageProfile(image,"icc"); if (profile == (StringInfo *) NULL) ThrowWriterException(CoderError,"NoColorProfileIsAvailable"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) CloseBlob(image); return(MagickTrue); } return(MagickFalse); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5301_0
crossvul-cpp_data_bad_353_0
/* * Copyright (C) Andrew Tridgell 1995-1999 * * This software may be distributed either under the terms of the * BSD-style license that accompanies tcpdump or the GNU GPL version 2 * or later */ /* \summary: SMB/CIFS printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "smb.h" static const char tstr[] = "[|SMB]"; static int request = 0; static int unicodestr = 0; const u_char *startbuf = NULL; struct smbdescript { const char *req_f1; const char *req_f2; const char *rep_f1; const char *rep_f2; void (*fn)(netdissect_options *, const u_char *, const u_char *, const u_char *, const u_char *); }; struct smbdescriptint { const char *req_f1; const char *req_f2; const char *rep_f1; const char *rep_f2; void (*fn)(netdissect_options *, const u_char *, const u_char *, int, int); }; struct smbfns { int id; const char *name; int flags; struct smbdescript descript; }; struct smbfnsint { int id; const char *name; int flags; struct smbdescriptint descript; }; #define DEFDESCRIPT { NULL, NULL, NULL, NULL, NULL } #define FLG_CHAIN (1 << 0) static const struct smbfns * smbfind(int id, const struct smbfns *list) { int sindex; for (sindex = 0; list[sindex].name; sindex++) if (list[sindex].id == id) return(&list[sindex]); return(&list[0]); } static const struct smbfnsint * smbfindint(int id, const struct smbfnsint *list) { int sindex; for (sindex = 0; list[sindex].name; sindex++) if (list[sindex].id == id) return(&list[sindex]); return(&list[0]); } static void trans2_findfirst(netdissect_options *ndo, const u_char *param, const u_char *data, int pcnt, int dcnt) { const char *fmt; if (request) fmt = "Attribute=[A]\nSearchCount=[d]\nFlags=[w]\nLevel=[dP4]\nFile=[S]\n"; else fmt = "Handle=[w]\nCount=[d]\nEOS=[w]\nEoffset=[d]\nLastNameOfs=[w]\n"; smb_fdata(ndo, param, fmt, param + pcnt, unicodestr); if (dcnt) { ND_PRINT((ndo, "data:\n")); smb_print_data(ndo, data, dcnt); } } static void trans2_qfsinfo(netdissect_options *ndo, const u_char *param, const u_char *data, int pcnt, int dcnt) { static int level = 0; const char *fmt=""; if (request) { ND_TCHECK2(*param, 2); level = EXTRACT_LE_16BITS(param); fmt = "InfoLevel=[d]\n"; smb_fdata(ndo, param, fmt, param + pcnt, unicodestr); } else { switch (level) { case 1: fmt = "idFileSystem=[W]\nSectorUnit=[D]\nUnit=[D]\nAvail=[D]\nSectorSize=[d]\n"; break; case 2: fmt = "CreationTime=[T2]VolNameLength=[lb]\nVolumeLabel=[c]\n"; break; case 0x105: fmt = "Capabilities=[W]\nMaxFileLen=[D]\nVolNameLen=[lD]\nVolume=[C]\n"; break; default: fmt = "UnknownLevel\n"; break; } smb_fdata(ndo, data, fmt, data + dcnt, unicodestr); } if (dcnt) { ND_PRINT((ndo, "data:\n")); smb_print_data(ndo, data, dcnt); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static const struct smbfnsint trans2_fns[] = { { 0, "TRANSACT2_OPEN", 0, { "Flags2=[w]\nMode=[w]\nSearchAttrib=[A]\nAttrib=[A]\nTime=[T2]\nOFun=[w]\nSize=[D]\nRes=([w, w, w, w, w])\nPath=[S]", NULL, "Handle=[d]\nAttrib=[A]\nTime=[T2]\nSize=[D]\nAccess=[w]\nType=[w]\nState=[w]\nAction=[w]\nInode=[W]\nOffErr=[d]\n|EALength=[d]\n", NULL, NULL }}, { 1, "TRANSACT2_FINDFIRST", 0, { NULL, NULL, NULL, NULL, trans2_findfirst }}, { 2, "TRANSACT2_FINDNEXT", 0, DEFDESCRIPT }, { 3, "TRANSACT2_QFSINFO", 0, { NULL, NULL, NULL, NULL, trans2_qfsinfo }}, { 4, "TRANSACT2_SETFSINFO", 0, DEFDESCRIPT }, { 5, "TRANSACT2_QPATHINFO", 0, DEFDESCRIPT }, { 6, "TRANSACT2_SETPATHINFO", 0, DEFDESCRIPT }, { 7, "TRANSACT2_QFILEINFO", 0, DEFDESCRIPT }, { 8, "TRANSACT2_SETFILEINFO", 0, DEFDESCRIPT }, { 9, "TRANSACT2_FSCTL", 0, DEFDESCRIPT }, { 10, "TRANSACT2_IOCTL", 0, DEFDESCRIPT }, { 11, "TRANSACT2_FINDNOTIFYFIRST", 0, DEFDESCRIPT }, { 12, "TRANSACT2_FINDNOTIFYNEXT", 0, DEFDESCRIPT }, { 13, "TRANSACT2_MKDIR", 0, DEFDESCRIPT }, { -1, NULL, 0, DEFDESCRIPT } }; static void print_trans2(netdissect_options *ndo, const u_char *words, const u_char *dat, const u_char *buf, const u_char *maxbuf) { u_int bcc; static const struct smbfnsint *fn = &trans2_fns[0]; const u_char *data, *param; const u_char *w = words + 1; const char *f1 = NULL, *f2 = NULL; int pcnt, dcnt; ND_TCHECK(words[0]); if (request) { ND_TCHECK2(w[14 * 2], 2); pcnt = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); dcnt = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); fn = smbfindint(EXTRACT_LE_16BITS(w + 14 * 2), trans2_fns); } else { if (words[0] == 0) { ND_PRINT((ndo, "%s\n", fn->name)); ND_PRINT((ndo, "Trans2Interim\n")); return; } ND_TCHECK2(w[7 * 2], 2); pcnt = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); dcnt = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); } ND_PRINT((ndo, "%s param_length=%d data_length=%d\n", fn->name, pcnt, dcnt)); if (request) { if (words[0] == 8) { smb_fdata(ndo, words + 1, "Trans2Secondary\nTotParam=[d]\nTotData=[d]\nParamCnt=[d]\nParamOff=[d]\nParamDisp=[d]\nDataCnt=[d]\nDataOff=[d]\nDataDisp=[d]\nHandle=[d]\n", maxbuf, unicodestr); return; } else { smb_fdata(ndo, words + 1, "TotParam=[d]\nTotData=[d]\nMaxParam=[d]\nMaxData=[d]\nMaxSetup=[b][P1]\nFlags=[w]\nTimeOut=[D]\nRes1=[w]\nParamCnt=[d]\nParamOff=[d]\nDataCnt=[d]\nDataOff=[d]\nSetupCnt=[b][P1]\n", words + 1 + 14 * 2, unicodestr); } f1 = fn->descript.req_f1; f2 = fn->descript.req_f2; } else { smb_fdata(ndo, words + 1, "TotParam=[d]\nTotData=[d]\nRes1=[w]\nParamCnt=[d]\nParamOff=[d]\nParamDisp[d]\nDataCnt=[d]\nDataOff=[d]\nDataDisp=[d]\nSetupCnt=[b][P1]\n", words + 1 + 10 * 2, unicodestr); f1 = fn->descript.rep_f1; f2 = fn->descript.rep_f2; } ND_TCHECK2(*dat, 2); bcc = EXTRACT_LE_16BITS(dat); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (fn->descript.fn) (*fn->descript.fn)(ndo, param, data, pcnt, dcnt); else { smb_fdata(ndo, param, f1 ? f1 : "Parameters=\n", param + pcnt, unicodestr); smb_fdata(ndo, data, f2 ? f2 : "Data=\n", data + dcnt, unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_browse(netdissect_options *ndo, const u_char *param, int paramlen, const u_char *data, int datalen) { const u_char *maxbuf = data + datalen; int command; ND_TCHECK(data[0]); command = data[0]; smb_fdata(ndo, param, "BROWSE PACKET\n|Param ", param+paramlen, unicodestr); switch (command) { case 0xF: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (LocalMasterAnnouncement)\nUpdateCount=[w]\nRes1=[B]\nAnnounceInterval=[d]\nName=[n2]\nMajorVersion=[B]\nMinorVersion=[B]\nServerType=[W]\nElectionVersion=[w]\nBrowserConstant=[w]\n", maxbuf, unicodestr); break; case 0x1: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (HostAnnouncement)\nUpdateCount=[w]\nRes1=[B]\nAnnounceInterval=[d]\nName=[n2]\nMajorVersion=[B]\nMinorVersion=[B]\nServerType=[W]\nElectionVersion=[w]\nBrowserConstant=[w]\n", maxbuf, unicodestr); break; case 0x2: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (AnnouncementRequest)\nFlags=[B]\nReplySystemName=[S]\n", maxbuf, unicodestr); break; case 0xc: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (WorkgroupAnnouncement)\nUpdateCount=[w]\nRes1=[B]\nAnnounceInterval=[d]\nName=[n2]\nMajorVersion=[B]\nMinorVersion=[B]\nServerType=[W]\nCommentPointer=[W]\nServerName=[S]\n", maxbuf, unicodestr); break; case 0x8: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (ElectionFrame)\nElectionVersion=[B]\nOSSummary=[W]\nUptime=[(W, W)]\nServerName=[S]\n", maxbuf, unicodestr); break; case 0xb: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (BecomeBackupBrowser)\nName=[S]\n", maxbuf, unicodestr); break; case 0x9: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (GetBackupList)\nListCount?=[B]\nToken=[W]\n", maxbuf, unicodestr); break; case 0xa: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (BackupListResponse)\nServerCount?=[B]\nToken=[W]\n*Name=[S]\n", maxbuf, unicodestr); break; case 0xd: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (MasterAnnouncement)\nMasterName=[S]\n", maxbuf, unicodestr); break; case 0xe: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (ResetBrowser)\nOptions=[B]\n", maxbuf, unicodestr); break; default: data = smb_fdata(ndo, data, "Unknown Browser Frame ", maxbuf, unicodestr); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_ipc(netdissect_options *ndo, const u_char *param, int paramlen, const u_char *data, int datalen) { if (paramlen) smb_fdata(ndo, param, "Command=[w]\nStr1=[S]\nStr2=[S]\n", param + paramlen, unicodestr); if (datalen) smb_fdata(ndo, data, "IPC ", data + datalen, unicodestr); } static void print_trans(netdissect_options *ndo, const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf) { u_int bcc; const char *f1, *f2, *f3, *f4; const u_char *data, *param; const u_char *w = words + 1; int datalen, paramlen; if (request) { ND_TCHECK2(w[12 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); datalen = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n"; f2 = "|Name=[S]\n"; f3 = "|Param "; f4 = "|Data "; } else { ND_TCHECK2(w[7 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); datalen = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n"; f2 = "|Unknown "; f3 = "|Param "; f4 = "|Data "; } smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf), unicodestr); ND_TCHECK2(*data1, 2); bcc = EXTRACT_LE_16BITS(data1); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr); if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) { print_browse(ndo, param, paramlen, data, datalen); return; } if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) { print_ipc(ndo, param, paramlen, data, datalen); return; } if (paramlen) smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr); if (datalen) smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_negprot(netdissect_options *ndo, const u_char *words, const u_char *data, const u_char *buf _U_, const u_char *maxbuf) { u_int wct, bcc; const char *f1 = NULL, *f2 = NULL; ND_TCHECK(words[0]); wct = words[0]; if (request) f2 = "*|Dialect=[Y]\n"; else { if (wct == 1) f1 = "Core Protocol\nDialectIndex=[d]"; else if (wct == 17) f1 = "NT1 Protocol\nDialectIndex=[d]\nSecMode=[B]\nMaxMux=[d]\nNumVcs=[d]\nMaxBuffer=[D]\nRawSize=[D]\nSessionKey=[W]\nCapabilities=[W]\nServerTime=[T3]TimeZone=[d]\nCryptKey="; else if (wct == 13) f1 = "Coreplus/Lanman1/Lanman2 Protocol\nDialectIndex=[d]\nSecMode=[w]\nMaxXMit=[d]\nMaxMux=[d]\nMaxVcs=[d]\nBlkMode=[w]\nSessionKey=[W]\nServerTime=[T1]TimeZone=[d]\nRes=[W]\nCryptKey="; } if (f1) smb_fdata(ndo, words + 1, f1, min(words + 1 + wct * 2, maxbuf), unicodestr); else smb_print_data(ndo, words + 1, min(wct * 2, PTR_DIFF(maxbuf, words + 1))); ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { if (f2) smb_fdata(ndo, data + 2, f2, min(data + 2 + EXTRACT_LE_16BITS(data), maxbuf), unicodestr); else smb_print_data(ndo, data + 2, min(EXTRACT_LE_16BITS(data), PTR_DIFF(maxbuf, data + 2))); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_sesssetup(netdissect_options *ndo, const u_char *words, const u_char *data, const u_char *buf _U_, const u_char *maxbuf) { u_int wct, bcc; const char *f1 = NULL, *f2 = NULL; ND_TCHECK(words[0]); wct = words[0]; if (request) { if (wct == 10) f1 = "Com2=[w]\nOff2=[d]\nBufSize=[d]\nMpxMax=[d]\nVcNum=[d]\nSessionKey=[W]\nPassLen=[d]\nCryptLen=[d]\nCryptOff=[d]\nPass&Name=\n"; else f1 = "Com2=[B]\nRes1=[B]\nOff2=[d]\nMaxBuffer=[d]\nMaxMpx=[d]\nVcNumber=[d]\nSessionKey=[W]\nCaseInsensitivePasswordLength=[d]\nCaseSensitivePasswordLength=[d]\nRes=[W]\nCapabilities=[W]\nPass1&Pass2&Account&Domain&OS&LanMan=\n"; } else { if (wct == 3) { f1 = "Com2=[w]\nOff2=[d]\nAction=[w]\n"; } else if (wct == 13) { f1 = "Com2=[B]\nRes=[B]\nOff2=[d]\nAction=[w]\n"; f2 = "NativeOS=[S]\nNativeLanMan=[S]\nPrimaryDomain=[S]\n"; } } if (f1) smb_fdata(ndo, words + 1, f1, min(words + 1 + wct * 2, maxbuf), unicodestr); else smb_print_data(ndo, words + 1, min(wct * 2, PTR_DIFF(maxbuf, words + 1))); ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { if (f2) smb_fdata(ndo, data + 2, f2, min(data + 2 + EXTRACT_LE_16BITS(data), maxbuf), unicodestr); else smb_print_data(ndo, data + 2, min(EXTRACT_LE_16BITS(data), PTR_DIFF(maxbuf, data + 2))); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_lockingandx(netdissect_options *ndo, const u_char *words, const u_char *data, const u_char *buf _U_, const u_char *maxbuf) { u_int wct, bcc; const u_char *maxwords; const char *f1 = NULL, *f2 = NULL; ND_TCHECK(words[0]); wct = words[0]; if (request) { f1 = "Com2=[w]\nOff2=[d]\nHandle=[d]\nLockType=[w]\nTimeOut=[D]\nUnlockCount=[d]\nLockCount=[d]\n"; ND_TCHECK(words[7]); if (words[7] & 0x10) f2 = "*Process=[d]\n[P2]Offset=[M]\nLength=[M]\n"; else f2 = "*Process=[d]\nOffset=[D]\nLength=[D]\n"; } else { f1 = "Com2=[w]\nOff2=[d]\n"; } maxwords = min(words + 1 + wct * 2, maxbuf); if (wct) smb_fdata(ndo, words + 1, f1, maxwords, unicodestr); ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { if (f2) smb_fdata(ndo, data + 2, f2, min(data + 2 + EXTRACT_LE_16BITS(data), maxbuf), unicodestr); else smb_print_data(ndo, data + 2, min(EXTRACT_LE_16BITS(data), PTR_DIFF(maxbuf, data + 2))); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static const struct smbfns smb_fns[] = { { -1, "SMBunknown", 0, DEFDESCRIPT }, { SMBtcon, "SMBtcon", 0, { NULL, "Path=[Z]\nPassword=[Z]\nDevice=[Z]\n", "MaxXmit=[d]\nTreeId=[d]\n", NULL, NULL } }, { SMBtdis, "SMBtdis", 0, DEFDESCRIPT }, { SMBexit, "SMBexit", 0, DEFDESCRIPT }, { SMBioctl, "SMBioctl", 0, DEFDESCRIPT }, { SMBecho, "SMBecho", 0, { "ReverbCount=[d]\n", NULL, "SequenceNum=[d]\n", NULL, NULL } }, { SMBulogoffX, "SMBulogoffX", FLG_CHAIN, DEFDESCRIPT }, { SMBgetatr, "SMBgetatr", 0, { NULL, "Path=[Z]\n", "Attribute=[A]\nTime=[T2]Size=[D]\nRes=([w,w,w,w,w])\n", NULL, NULL } }, { SMBsetatr, "SMBsetatr", 0, { "Attribute=[A]\nTime=[T2]Res=([w,w,w,w,w])\n", "Path=[Z]\n", NULL, NULL, NULL } }, { SMBchkpth, "SMBchkpth", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBsearch, "SMBsearch", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBopen, "SMBopen", 0, { "Mode=[w]\nAttribute=[A]\n", "Path=[Z]\n", "Handle=[d]\nOAttrib=[A]\nTime=[T2]Size=[D]\nAccess=[w]\n", NULL, NULL } }, { SMBcreate, "SMBcreate", 0, { "Attrib=[A]\nTime=[T2]", "Path=[Z]\n", "Handle=[d]\n", NULL, NULL } }, { SMBmknew, "SMBmknew", 0, { "Attrib=[A]\nTime=[T2]", "Path=[Z]\n", "Handle=[d]\n", NULL, NULL } }, { SMBunlink, "SMBunlink", 0, { "Attrib=[A]\n", "Path=[Z]\n", NULL, NULL, NULL } }, { SMBread, "SMBread", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\nRes=([w,w,w,w])\n", NULL, NULL } }, { SMBwrite, "SMBwrite", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\n", NULL, NULL } }, { SMBclose, "SMBclose", 0, { "Handle=[d]\nTime=[T2]", NULL, NULL, NULL, NULL } }, { SMBmkdir, "SMBmkdir", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBrmdir, "SMBrmdir", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBdskattr, "SMBdskattr", 0, { NULL, NULL, "TotalUnits=[d]\nBlocksPerUnit=[d]\nBlockSize=[d]\nFreeUnits=[d]\nMedia=[w]\n", NULL, NULL } }, { SMBmv, "SMBmv", 0, { "Attrib=[A]\n", "OldPath=[Z]\nNewPath=[Z]\n", NULL, NULL, NULL } }, /* * this is a Pathworks specific call, allowing the * changing of the root path */ { pSETDIR, "SMBsetdir", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBlseek, "SMBlseek", 0, { "Handle=[d]\nMode=[w]\nOffset=[D]\n", "Offset=[D]\n", NULL, NULL, NULL } }, { SMBflush, "SMBflush", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsplopen, "SMBsplopen", 0, { "SetupLen=[d]\nMode=[w]\n", "Ident=[Z]\n", "Handle=[d]\n", NULL, NULL } }, { SMBsplclose, "SMBsplclose", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsplretq, "SMBsplretq", 0, { "MaxCount=[d]\nStartIndex=[d]\n", NULL, "Count=[d]\nIndex=[d]\n", "*Time=[T2]Status=[B]\nJobID=[d]\nSize=[D]\nRes=[B]Name=[s16]\n", NULL } }, { SMBsplwr, "SMBsplwr", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBlock, "SMBlock", 0, { "Handle=[d]\nCount=[D]\nOffset=[D]\n", NULL, NULL, NULL, NULL } }, { SMBunlock, "SMBunlock", 0, { "Handle=[d]\nCount=[D]\nOffset=[D]\n", NULL, NULL, NULL, NULL } }, /* CORE+ PROTOCOL FOLLOWS */ { SMBreadbraw, "SMBreadbraw", 0, { "Handle=[d]\nOffset=[D]\nMaxCount=[d]\nMinCount=[d]\nTimeOut=[D]\nRes=[d]\n", NULL, NULL, NULL, NULL } }, { SMBwritebraw, "SMBwritebraw", 0, { "Handle=[d]\nTotalCount=[d]\nRes=[w]\nOffset=[D]\nTimeOut=[D]\nWMode=[w]\nRes2=[W]\n|DataSize=[d]\nDataOff=[d]\n", NULL, "WriteRawAck", NULL, NULL } }, { SMBwritec, "SMBwritec", 0, { NULL, NULL, "Count=[d]\n", NULL, NULL } }, { SMBwriteclose, "SMBwriteclose", 0, { "Handle=[d]\nCount=[d]\nOffset=[D]\nTime=[T2]Res=([w,w,w,w,w,w])", NULL, "Count=[d]\n", NULL, NULL } }, { SMBlockread, "SMBlockread", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\nRes=([w,w,w,w])\n", NULL, NULL } }, { SMBwriteunlock, "SMBwriteunlock", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\n", NULL, NULL } }, { SMBreadBmpx, "SMBreadBmpx", 0, { "Handle=[d]\nOffset=[D]\nMaxCount=[d]\nMinCount=[d]\nTimeOut=[D]\nRes=[w]\n", NULL, "Offset=[D]\nTotCount=[d]\nRemaining=[d]\nRes=([w,w])\nDataSize=[d]\nDataOff=[d]\n", NULL, NULL } }, { SMBwriteBmpx, "SMBwriteBmpx", 0, { "Handle=[d]\nTotCount=[d]\nRes=[w]\nOffset=[D]\nTimeOut=[D]\nWMode=[w]\nRes2=[W]\nDataSize=[d]\nDataOff=[d]\n", NULL, "Remaining=[d]\n", NULL, NULL } }, { SMBwriteBs, "SMBwriteBs", 0, { "Handle=[d]\nTotCount=[d]\nOffset=[D]\nRes=[W]\nDataSize=[d]\nDataOff=[d]\n", NULL, "Count=[d]\n", NULL, NULL } }, { SMBsetattrE, "SMBsetattrE", 0, { "Handle=[d]\nCreationTime=[T2]AccessTime=[T2]ModifyTime=[T2]", NULL, NULL, NULL, NULL } }, { SMBgetattrE, "SMBgetattrE", 0, { "Handle=[d]\n", NULL, "CreationTime=[T2]AccessTime=[T2]ModifyTime=[T2]Size=[D]\nAllocSize=[D]\nAttribute=[A]\n", NULL, NULL } }, { SMBtranss, "SMBtranss", 0, DEFDESCRIPT }, { SMBioctls, "SMBioctls", 0, DEFDESCRIPT }, { SMBcopy, "SMBcopy", 0, { "TreeID2=[d]\nOFun=[w]\nFlags=[w]\n", "Path=[S]\nNewPath=[S]\n", "CopyCount=[d]\n", "|ErrStr=[S]\n", NULL } }, { SMBmove, "SMBmove", 0, { "TreeID2=[d]\nOFun=[w]\nFlags=[w]\n", "Path=[S]\nNewPath=[S]\n", "MoveCount=[d]\n", "|ErrStr=[S]\n", NULL } }, { SMBopenX, "SMBopenX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nFlags=[w]\nMode=[w]\nSearchAttrib=[A]\nAttrib=[A]\nTime=[T2]OFun=[w]\nSize=[D]\nTimeOut=[D]\nRes=[W]\n", "Path=[S]\n", "Com2=[w]\nOff2=[d]\nHandle=[d]\nAttrib=[A]\nTime=[T2]Size=[D]\nAccess=[w]\nType=[w]\nState=[w]\nAction=[w]\nFileID=[W]\nRes=[w]\n", NULL, NULL } }, { SMBreadX, "SMBreadX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nHandle=[d]\nOffset=[D]\nMaxCount=[d]\nMinCount=[d]\nTimeOut=[D]\nCountLeft=[d]\n", NULL, "Com2=[w]\nOff2=[d]\nRemaining=[d]\nRes=[W]\nDataSize=[d]\nDataOff=[d]\nRes=([w,w,w,w])\n", NULL, NULL } }, { SMBwriteX, "SMBwriteX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nHandle=[d]\nOffset=[D]\nTimeOut=[D]\nWMode=[w]\nCountLeft=[d]\nRes=[w]\nDataSize=[d]\nDataOff=[d]\n", NULL, "Com2=[w]\nOff2=[d]\nCount=[d]\nRemaining=[d]\nRes=[W]\n", NULL, NULL } }, { SMBffirst, "SMBffirst", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBfunique, "SMBfunique", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBfclose, "SMBfclose", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBfindnclose, "SMBfindnclose", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBfindclose, "SMBfindclose", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsends, "SMBsends", 0, { NULL, "Source=[Z]\nDest=[Z]\n", NULL, NULL, NULL } }, { SMBsendstrt, "SMBsendstrt", 0, { NULL, "Source=[Z]\nDest=[Z]\n", "GroupID=[d]\n", NULL, NULL } }, { SMBsendend, "SMBsendend", 0, { "GroupID=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsendtxt, "SMBsendtxt", 0, { "GroupID=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsendb, "SMBsendb", 0, { NULL, "Source=[Z]\nDest=[Z]\n", NULL, NULL, NULL } }, { SMBfwdname, "SMBfwdname", 0, DEFDESCRIPT }, { SMBcancelf, "SMBcancelf", 0, DEFDESCRIPT }, { SMBgetmac, "SMBgetmac", 0, DEFDESCRIPT }, { SMBnegprot, "SMBnegprot", 0, { NULL, NULL, NULL, NULL, print_negprot } }, { SMBsesssetupX, "SMBsesssetupX", FLG_CHAIN, { NULL, NULL, NULL, NULL, print_sesssetup } }, { SMBtconX, "SMBtconX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nFlags=[w]\nPassLen=[d]\nPasswd&Path&Device=\n", NULL, "Com2=[w]\nOff2=[d]\n", "ServiceType=[R]\n", NULL } }, { SMBlockingX, "SMBlockingX", FLG_CHAIN, { NULL, NULL, NULL, NULL, print_lockingandx } }, { SMBtrans2, "SMBtrans2", 0, { NULL, NULL, NULL, NULL, print_trans2 } }, { SMBtranss2, "SMBtranss2", 0, DEFDESCRIPT }, { SMBctemp, "SMBctemp", 0, DEFDESCRIPT }, { SMBreadBs, "SMBreadBs", 0, DEFDESCRIPT }, { SMBtrans, "SMBtrans", 0, { NULL, NULL, NULL, NULL, print_trans } }, { SMBnttrans, "SMBnttrans", 0, DEFDESCRIPT }, { SMBnttranss, "SMBnttranss", 0, DEFDESCRIPT }, { SMBntcreateX, "SMBntcreateX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nRes=[b]\nNameLen=[ld]\nFlags=[W]\nRootDirectoryFid=[D]\nAccessMask=[W]\nAllocationSize=[L]\nExtFileAttributes=[W]\nShareAccess=[W]\nCreateDisposition=[W]\nCreateOptions=[W]\nImpersonationLevel=[W]\nSecurityFlags=[b]\n", "Path=[C]\n", "Com2=[w]\nOff2=[d]\nOplockLevel=[b]\nFid=[d]\nCreateAction=[W]\nCreateTime=[T3]LastAccessTime=[T3]LastWriteTime=[T3]ChangeTime=[T3]ExtFileAttributes=[W]\nAllocationSize=[L]\nEndOfFile=[L]\nFileType=[w]\nDeviceState=[w]\nDirectory=[b]\n", NULL, NULL } }, { SMBntcancel, "SMBntcancel", 0, DEFDESCRIPT }, { -1, NULL, 0, DEFDESCRIPT } }; /* * print a SMB message */ static void print_smb(netdissect_options *ndo, const u_char *buf, const u_char *maxbuf) { uint16_t flags2; int nterrcodes; int command; uint32_t nterror; const u_char *words, *maxwords, *data; const struct smbfns *fn; const char *fmt_smbheader = "[P4]SMB Command = [B]\nError class = [BP1]\nError code = [d]\nFlags1 = [B]\nFlags2 = [B][P13]\nTree ID = [d]\nProc ID = [d]\nUID = [d]\nMID = [d]\nWord Count = [b]\n"; int smboffset; ND_TCHECK(buf[9]); request = (buf[9] & 0x80) ? 0 : 1; startbuf = buf; command = buf[4]; fn = smbfind(command, smb_fns); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n")); ND_PRINT((ndo, "SMB PACKET: %s (%s)\n", fn->name, request ? "REQUEST" : "REPLY")); if (ndo->ndo_vflag < 2) return; ND_TCHECK_16BITS(&buf[10]); flags2 = EXTRACT_LE_16BITS(&buf[10]); unicodestr = flags2 & 0x8000; nterrcodes = flags2 & 0x4000; /* print out the header */ smb_fdata(ndo, buf, fmt_smbheader, buf + 33, unicodestr); if (nterrcodes) { nterror = EXTRACT_LE_32BITS(&buf[5]); if (nterror) ND_PRINT((ndo, "NTError = %s\n", nt_errstr(nterror))); } else { if (buf[5]) ND_PRINT((ndo, "SMBError = %s\n", smb_errstr(buf[5], EXTRACT_LE_16BITS(&buf[7])))); } smboffset = 32; for (;;) { const char *f1, *f2; int wct; u_int bcc; int newsmboffset; words = buf + smboffset; ND_TCHECK(words[0]); wct = words[0]; data = words + 1 + wct * 2; maxwords = min(data, maxbuf); if (request) { f1 = fn->descript.req_f1; f2 = fn->descript.req_f2; } else { f1 = fn->descript.rep_f1; f2 = fn->descript.rep_f2; } if (fn->descript.fn) (*fn->descript.fn)(ndo, words, data, buf, maxbuf); else { if (wct) { if (f1) smb_fdata(ndo, words + 1, f1, words + 1 + wct * 2, unicodestr); else { int i; int v; for (i = 0; &words[1 + 2 * i] < maxwords; i++) { ND_TCHECK2(words[1 + 2 * i], 2); v = EXTRACT_LE_16BITS(words + 1 + 2 * i); ND_PRINT((ndo, "smb_vwv[%d]=%d (0x%X)\n", i, v, v)); } } } ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (f2) { if (bcc > 0) smb_fdata(ndo, data + 2, f2, data + 2 + bcc, unicodestr); } else { if (bcc > 0) { ND_PRINT((ndo, "smb_buf[]=\n")); smb_print_data(ndo, data + 2, min(bcc, PTR_DIFF(maxbuf, data + 2))); } } } if ((fn->flags & FLG_CHAIN) == 0) break; if (wct == 0) break; ND_TCHECK(words[1]); command = words[1]; if (command == 0xFF) break; ND_TCHECK2(words[3], 2); newsmboffset = EXTRACT_LE_16BITS(words + 3); fn = smbfind(command, smb_fns); ND_PRINT((ndo, "\nSMB PACKET: %s (%s) (CHAINED)\n", fn->name, request ? "REQUEST" : "REPLY")); if (newsmboffset <= smboffset) { ND_PRINT((ndo, "Bad andX offset: %u <= %u\n", newsmboffset, smboffset)); break; } smboffset = newsmboffset; } ND_PRINT((ndo, "\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * print a NBT packet received across tcp on port 139 */ void nbt_tcp_print(netdissect_options *ndo, const u_char *data, int length) { int caplen; int type; u_int nbt_len; const u_char *maxbuf; if (length < 4) goto trunc; if (ndo->ndo_snapend < data) goto trunc; caplen = ndo->ndo_snapend - data; if (caplen < 4) goto trunc; maxbuf = data + caplen; ND_TCHECK_8BITS(data); type = data[0]; ND_TCHECK_16BITS(data + 2); nbt_len = EXTRACT_16BITS(data + 2); length -= 4; caplen -= 4; startbuf = data; if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, " NBT Session Packet: ")); switch (type) { case 0x00: ND_PRINT((ndo, "Session Message")); break; case 0x81: ND_PRINT((ndo, "Session Request")); break; case 0x82: ND_PRINT((ndo, "Session Granted")); break; case 0x83: { int ecode; if (nbt_len < 4) goto trunc; if (length < 4) goto trunc; if (caplen < 4) goto trunc; ecode = data[4]; ND_PRINT((ndo, "Session Reject, ")); switch (ecode) { case 0x80: ND_PRINT((ndo, "Not listening on called name")); break; case 0x81: ND_PRINT((ndo, "Not listening for calling name")); break; case 0x82: ND_PRINT((ndo, "Called name not present")); break; case 0x83: ND_PRINT((ndo, "Called name present, but insufficient resources")); break; default: ND_PRINT((ndo, "Unspecified error 0x%X", ecode)); break; } } break; case 0x85: ND_PRINT((ndo, "Session Keepalive")); break; default: data = smb_fdata(ndo, data, "Unknown packet type [rB]", maxbuf, 0); break; } } else { ND_PRINT((ndo, "\n>>> NBT Session Packet\n")); switch (type) { case 0x00: data = smb_fdata(ndo, data, "[P1]NBT Session Message\nFlags=[B]\nLength=[rd]\n", data + 4, 0); if (data == NULL) break; if (nbt_len >= 4 && caplen >= 4 && memcmp(data,"\377SMB",4) == 0) { if ((int)nbt_len > caplen) { if ((int)nbt_len > length) ND_PRINT((ndo, "WARNING: Packet is continued in later TCP segments\n")); else ND_PRINT((ndo, "WARNING: Short packet. Try increasing the snap length by %d\n", nbt_len - caplen)); } print_smb(ndo, data, maxbuf > data + nbt_len ? data + nbt_len : maxbuf); } else ND_PRINT((ndo, "Session packet:(raw data or continuation?)\n")); break; case 0x81: data = smb_fdata(ndo, data, "[P1]NBT Session Request\nFlags=[B]\nLength=[rd]\nDestination=[n1]\nSource=[n1]\n", maxbuf, 0); break; case 0x82: data = smb_fdata(ndo, data, "[P1]NBT Session Granted\nFlags=[B]\nLength=[rd]\n", maxbuf, 0); break; case 0x83: { const u_char *origdata; int ecode; origdata = data; data = smb_fdata(ndo, data, "[P1]NBT SessionReject\nFlags=[B]\nLength=[rd]\nReason=[B]\n", maxbuf, 0); if (data == NULL) break; if (nbt_len >= 1 && caplen >= 1) { ecode = origdata[4]; switch (ecode) { case 0x80: ND_PRINT((ndo, "Not listening on called name\n")); break; case 0x81: ND_PRINT((ndo, "Not listening for calling name\n")); break; case 0x82: ND_PRINT((ndo, "Called name not present\n")); break; case 0x83: ND_PRINT((ndo, "Called name present, but insufficient resources\n")); break; default: ND_PRINT((ndo, "Unspecified error 0x%X\n", ecode)); break; } } } break; case 0x85: data = smb_fdata(ndo, data, "[P1]NBT Session Keepalive\nFlags=[B]\nLength=[rd]\n", maxbuf, 0); break; default: data = smb_fdata(ndo, data, "NBT - Unknown packet type\nType=[B]\n", maxbuf, 0); break; } ND_PRINT((ndo, "\n")); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static const struct tok opcode_str[] = { { 0, "QUERY" }, { 5, "REGISTRATION" }, { 6, "RELEASE" }, { 7, "WACK" }, { 8, "REFRESH(8)" }, { 9, "REFRESH" }, { 15, "MULTIHOMED REGISTRATION" }, { 0, NULL } }; /* * print a NBT packet received across udp on port 137 */ void nbt_udp137_print(netdissect_options *ndo, const u_char *data, int length) { const u_char *maxbuf = data + length; int name_trn_id, response, opcode, nm_flags, rcode; int qdcount, ancount, nscount, arcount; const u_char *p; int total, i; ND_TCHECK2(data[10], 2); name_trn_id = EXTRACT_16BITS(data); response = (data[2] >> 7); opcode = (data[2] >> 3) & 0xF; nm_flags = ((data[2] & 0x7) << 4) + (data[3] >> 4); rcode = data[3] & 0xF; qdcount = EXTRACT_16BITS(data + 4); ancount = EXTRACT_16BITS(data + 6); nscount = EXTRACT_16BITS(data + 8); arcount = EXTRACT_16BITS(data + 10); startbuf = data; if (maxbuf <= data) return; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n>>> ")); ND_PRINT((ndo, "NBT UDP PACKET(137): %s", tok2str(opcode_str, "OPUNKNOWN", opcode))); if (response) { ND_PRINT((ndo, "; %s", rcode ? "NEGATIVE" : "POSITIVE")); } ND_PRINT((ndo, "; %s; %s", response ? "RESPONSE" : "REQUEST", (nm_flags & 1) ? "BROADCAST" : "UNICAST")); if (ndo->ndo_vflag < 2) return; ND_PRINT((ndo, "\nTrnID=0x%X\nOpCode=%d\nNmFlags=0x%X\nRcode=%d\nQueryCount=%d\nAnswerCount=%d\nAuthorityCount=%d\nAddressRecCount=%d\n", name_trn_id, opcode, nm_flags, rcode, qdcount, ancount, nscount, arcount)); p = data + 12; total = ancount + nscount + arcount; if (qdcount > 100 || total > 100) { ND_PRINT((ndo, "Corrupt packet??\n")); return; } if (qdcount) { ND_PRINT((ndo, "QuestionRecords:\n")); for (i = 0; i < qdcount; i++) { p = smb_fdata(ndo, p, "|Name=[n1]\nQuestionType=[rw]\nQuestionClass=[rw]\n#", maxbuf, 0); if (p == NULL) goto out; } } if (total) { ND_PRINT((ndo, "\nResourceRecords:\n")); for (i = 0; i < total; i++) { int rdlen; int restype; p = smb_fdata(ndo, p, "Name=[n1]\n#", maxbuf, 0); if (p == NULL) goto out; ND_TCHECK_16BITS(p); restype = EXTRACT_16BITS(p); p = smb_fdata(ndo, p, "ResType=[rw]\nResClass=[rw]\nTTL=[rD]\n", p + 8, 0); if (p == NULL) goto out; ND_TCHECK_16BITS(p); rdlen = EXTRACT_16BITS(p); ND_PRINT((ndo, "ResourceLength=%d\nResourceData=\n", rdlen)); p += 2; if (rdlen == 6) { p = smb_fdata(ndo, p, "AddrType=[rw]\nAddress=[b.b.b.b]\n", p + rdlen, 0); if (p == NULL) goto out; } else { if (restype == 0x21) { int numnames; ND_TCHECK(*p); numnames = p[0]; p = smb_fdata(ndo, p, "NumNames=[B]\n", p + 1, 0); if (p == NULL) goto out; while (numnames--) { p = smb_fdata(ndo, p, "Name=[n2]\t#", maxbuf, 0); if (p == NULL) goto out; ND_TCHECK(*p); if (p[0] & 0x80) ND_PRINT((ndo, "<GROUP> ")); switch (p[0] & 0x60) { case 0x00: ND_PRINT((ndo, "B ")); break; case 0x20: ND_PRINT((ndo, "P ")); break; case 0x40: ND_PRINT((ndo, "M ")); break; case 0x60: ND_PRINT((ndo, "_ ")); break; } if (p[0] & 0x10) ND_PRINT((ndo, "<DEREGISTERING> ")); if (p[0] & 0x08) ND_PRINT((ndo, "<CONFLICT> ")); if (p[0] & 0x04) ND_PRINT((ndo, "<ACTIVE> ")); if (p[0] & 0x02) ND_PRINT((ndo, "<PERMANENT> ")); ND_PRINT((ndo, "\n")); p += 2; } } else { smb_print_data(ndo, p, min(rdlen, length - (p - data))); p += rdlen; } } } } if (p < maxbuf) smb_fdata(ndo, p, "AdditionalData:\n", maxbuf, 0); out: ND_PRINT((ndo, "\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * Print an SMB-over-TCP packet received across tcp on port 445 */ void smb_tcp_print(netdissect_options *ndo, const u_char * data, int length) { int caplen; u_int smb_len; const u_char *maxbuf; if (length < 4) goto trunc; if (ndo->ndo_snapend < data) goto trunc; caplen = ndo->ndo_snapend - data; if (caplen < 4) goto trunc; maxbuf = data + caplen; smb_len = EXTRACT_24BITS(data + 1); length -= 4; caplen -= 4; startbuf = data; data += 4; if (smb_len >= 4 && caplen >= 4 && memcmp(data,"\377SMB",4) == 0) { if ((int)smb_len > caplen) { if ((int)smb_len > length) ND_PRINT((ndo, " WARNING: Packet is continued in later TCP segments\n")); else ND_PRINT((ndo, " WARNING: Short packet. Try increasing the snap length by %d\n", smb_len - caplen)); } else ND_PRINT((ndo, " ")); print_smb(ndo, data, maxbuf > data + smb_len ? data + smb_len : maxbuf); } else ND_PRINT((ndo, " SMB-over-TCP packet:(raw data or continuation?)\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * print a NBT packet received across udp on port 138 */ void nbt_udp138_print(netdissect_options *ndo, const u_char *data, int length) { const u_char *maxbuf = data + length; if (maxbuf > ndo->ndo_snapend) maxbuf = ndo->ndo_snapend; if (maxbuf <= data) return; startbuf = data; if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, "NBT UDP PACKET(138)")); return; } data = smb_fdata(ndo, data, "\n>>> NBT UDP PACKET(138) Res=[rw] ID=[rw] IP=[b.b.b.b] Port=[rd] Length=[rd] Res2=[rw]\nSourceName=[n1]\nDestName=[n1]\n#", maxbuf, 0); if (data != NULL) { /* If there isn't enough data for "\377SMB", don't check for it. */ if (&data[3] >= maxbuf) goto out; if (memcmp(data, "\377SMB",4) == 0) print_smb(ndo, data, maxbuf); } out: ND_PRINT((ndo, "\n")); } /* print netbeui frames */ static struct nbf_strings { const char *name; const char *nonverbose; const char *verbose; } nbf_strings[0x20] = { { "Add Group Name Query", ", [P23]Name to add=[n2]#", "[P5]ResponseCorrelator=[w]\n[P16]Name to add=[n2]\n" }, { "Add Name Query", ", [P23]Name to add=[n2]#", "[P5]ResponseCorrelator=[w]\n[P16]Name to add=[n2]\n" }, { "Name In Conflict", NULL, NULL }, { "Status Query", NULL, NULL }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Terminate Trace", NULL, NULL }, { "Datagram", NULL, "[P7]Destination=[n2]\nSource=[n2]\n" }, { "Broadcast Datagram", NULL, "[P7]Destination=[n2]\nSource=[n2]\n" }, { "Name Query", ", [P7]Name=[n2]#", "[P1]SessionNumber=[B]\nNameType=[B][P2]\nResponseCorrelator=[w]\nName=[n2]\nName of sender=[n2]\n" }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Add Name Response", ", [P1]GroupName=[w] [P4]Destination=[n2] Source=[n2]#", "AddNameInProcess=[B]\nGroupName=[w]\nTransmitCorrelator=[w][P2]\nDestination=[n2]\nSource=[n2]\n" }, { "Name Recognized", NULL, "[P1]Data2=[w]\nTransmitCorrelator=[w]\nResponseCorelator=[w]\nDestination=[n2]\nSource=[n2]\n" }, { "Status Response", NULL, NULL }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Terminate Trace", NULL, NULL }, { "Data Ack", NULL, "[P3]TransmitCorrelator=[w][P2]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Data First/Middle", NULL, "Flags=[{RECEIVE_CONTINUE|NO_ACK||PIGGYBACK_ACK_INCLUDED|}]\nResyncIndicator=[w][P2]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Data Only/Last", NULL, "Flags=[{|NO_ACK|PIGGYBACK_ACK_ALLOWED|PIGGYBACK_ACK_INCLUDED|}]\nResyncIndicator=[w][P2]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Session Confirm", NULL, "Data1=[B]\nData2=[w]\nTransmitCorrelator=[w]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Session End", NULL, "[P1]Data2=[w][P4]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Session Initialize", NULL, "Data1=[B]\nData2=[w]\nTransmitCorrelator=[w]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "No Receive", NULL, "Flags=[{|SEND_NO_ACK}]\nDataBytesAccepted=[b][P4]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Receive Outstanding", NULL, "[P1]DataBytesAccepted=[b][P4]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Receive Continue", NULL, "[P2]TransmitCorrelator=[w]\n[P2]RemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Session Alive", NULL, NULL } }; void netbeui_print(netdissect_options *ndo, u_short control, const u_char *data, int length) { const u_char *maxbuf = data + length; int len; int command; const u_char *data2; int is_truncated = 0; if (maxbuf > ndo->ndo_snapend) maxbuf = ndo->ndo_snapend; ND_TCHECK(data[4]); len = EXTRACT_LE_16BITS(data); command = data[4]; data2 = data + len; if (data2 >= maxbuf) { data2 = maxbuf; is_truncated = 1; } startbuf = data; if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, "NBF Packet: ")); data = smb_fdata(ndo, data, "[P5]#", maxbuf, 0); } else { ND_PRINT((ndo, "\n>>> NBF Packet\nType=0x%X ", control)); data = smb_fdata(ndo, data, "Length=[d] Signature=[w] Command=[B]\n#", maxbuf, 0); } if (data == NULL) goto out; if (command > 0x1f || nbf_strings[command].name == NULL) { if (ndo->ndo_vflag < 2) data = smb_fdata(ndo, data, "Unknown NBF Command#", data2, 0); else data = smb_fdata(ndo, data, "Unknown NBF Command\n", data2, 0); } else { if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, "%s", nbf_strings[command].name)); if (nbf_strings[command].nonverbose != NULL) data = smb_fdata(ndo, data, nbf_strings[command].nonverbose, data2, 0); } else { ND_PRINT((ndo, "%s:\n", nbf_strings[command].name)); if (nbf_strings[command].verbose != NULL) data = smb_fdata(ndo, data, nbf_strings[command].verbose, data2, 0); else ND_PRINT((ndo, "\n")); } } if (ndo->ndo_vflag < 2) return; if (data == NULL) goto out; if (is_truncated) { /* data2 was past the end of the buffer */ goto out; } /* If this isn't a command that would contain an SMB message, quit. */ if (command != 0x08 && command != 0x09 && command != 0x15 && command != 0x16) goto out; /* If there isn't enough data for "\377SMB", don't look for it. */ if (&data2[3] >= maxbuf) goto out; if (memcmp(data2, "\377SMB",4) == 0) print_smb(ndo, data2, maxbuf); else { int i; for (i = 0; i < 128; i++) { if (&data2[i + 3] >= maxbuf) break; if (memcmp(&data2[i], "\377SMB", 4) == 0) { ND_PRINT((ndo, "found SMB packet at %d\n", i)); print_smb(ndo, &data2[i], maxbuf); break; } } } out: ND_PRINT((ndo, "\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * print IPX-Netbios frames */ void ipx_netbios_print(netdissect_options *ndo, const u_char *data, u_int length) { /* * this is a hack till I work out how to parse the rest of the * NetBIOS-over-IPX stuff */ int i; const u_char *maxbuf; maxbuf = data + length; /* Don't go past the end of the captured data in the packet. */ if (maxbuf > ndo->ndo_snapend) maxbuf = ndo->ndo_snapend; startbuf = data; for (i = 0; i < 128; i++) { if (&data[i + 4] > maxbuf) break; if (memcmp(&data[i], "\377SMB", 4) == 0) { smb_fdata(ndo, data, "\n>>> IPX transport ", &data[i], 0); print_smb(ndo, &data[i], maxbuf); ND_PRINT((ndo, "\n")); break; } } if (i == 128) smb_fdata(ndo, data, "\n>>> Unknown IPX ", maxbuf, 0); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_353_0
crossvul-cpp_data_good_3181_0
/* radare - LGPL - Copyright 2011-2016 - pancake */ #include <r_cons.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_bin.h> #include "dex/dex.h" #define r_hash_adler32 __adler32 #include "../../hash/adler32.c" extern struct r_bin_dbginfo_t r_bin_dbginfo_dex; #define DEBUG_PRINTF 0 #if DEBUG_PRINTF #define dprintf eprintf #else #define dprintf if (0)eprintf #endif static bool dexdump = false; static Sdb *mdb = NULL; static Sdb *cdb = NULL; // TODO: remove if it is not used static char *getstr(RBinDexObj *bin, int idx) { ut8 buf[6]; ut64 len; int uleblen; if (!bin || idx < 0 || idx >= bin->header.strings_size || !bin->strings) { return NULL; } if (bin->strings[idx] >= bin->size) { return NULL; } if (r_buf_read_at (bin->b, bin->strings[idx], buf, sizeof (buf)) < 1) { return NULL; } uleblen = r_uleb128 (buf, sizeof (buf), &len) - buf; if (!uleblen || uleblen >= bin->size) { return NULL; } if (!len || len >= bin->size) { return NULL; } // TODO: improve this ugly fix char c = 'a'; while (c) { ut64 offset = bin->strings[idx] + uleblen + len; if (offset >= bin->size || offset < len) { return NULL; } r_buf_read_at (bin->b, offset, (ut8*)&c, 1); len++; } if ((int)len > 0 && len < R_BIN_SIZEOF_STRINGS) { char *str = calloc (1, len + 1); if (str) { r_buf_read_at (bin->b, (bin->strings[idx]) + uleblen, (ut8 *)str, len); str[len] = 0; return str; } } return NULL; } static int countOnes(ut32 val) { int count = 0; val = val - ((val >> 1) & 0x55555555); val = (val & 0x33333333) + ((val >> 2) & 0x33333333); count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; return count; } typedef enum { kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX } AccessFor; static char *createAccessFlagStr(ut32 flags, AccessFor forWhat) { #define NUM_FLAGS 18 static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = { { /* class, inner class */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "?", /* 0x0040 */ "?", /* 0x0080 */ "?", /* 0x0100 */ "INTERFACE", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "ANNOTATION", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "VERIFIED", /* 0x10000 */ "OPTIMIZED", /* 0x20000 */ }, { /* method */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "SYNCHRONIZED", /* 0x0020 */ "BRIDGE", /* 0x0040 */ "VARARGS", /* 0x0080 */ "NATIVE", /* 0x0100 */ "?", /* 0x0200 */ "ABSTRACT", /* 0x0400 */ "STRICT", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "?", /* 0x4000 */ "MIRANDA", /* 0x8000 */ "CONSTRUCTOR", /* 0x10000 */ "DECLARED_SYNCHRONIZED", /* 0x20000 */ }, { /* field */ "PUBLIC", /* 0x0001 */ "PRIVATE", /* 0x0002 */ "PROTECTED", /* 0x0004 */ "STATIC", /* 0x0008 */ "FINAL", /* 0x0010 */ "?", /* 0x0020 */ "VOLATILE", /* 0x0040 */ "TRANSIENT", /* 0x0080 */ "?", /* 0x0100 */ "?", /* 0x0200 */ "?", /* 0x0400 */ "?", /* 0x0800 */ "SYNTHETIC", /* 0x1000 */ "?", /* 0x2000 */ "ENUM", /* 0x4000 */ "?", /* 0x8000 */ "?", /* 0x10000 */ "?", /* 0x20000 */ }, }; const int kLongest = 21; int i, count; char* str; char* cp; count = countOnes(flags); // XXX check if this allocation is safe what if all the arithmetic // produces a huge number???? cp = str = (char*) malloc (count * (kLongest + 1) + 1); for (i = 0; i < NUM_FLAGS; i++) { if (flags & 0x01) { const char* accessStr = kAccessStrings[forWhat][i]; int len = strlen(accessStr); if (cp != str) { *cp++ = ' '; } memcpy(cp, accessStr, len); cp += len; } flags >>= 1; } *cp = '\0'; return str; } static char *dex_type_descriptor(RBinDexObj *bin, int type_idx) { if (type_idx < 0 || type_idx >= bin->header.types_size) { return NULL; } return getstr (bin, bin->types[type_idx].descriptor_id); } static char *dex_method_signature(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, type_id, list_size; char *r, *return_type = NULL, *signature = NULL, *buff = NULL; ut8 *bufptr; ut16 type_idx; int pos = 0, i, size = 1; if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { return NULL; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { return NULL; } type_id = bin->protos[proto_id].return_type_id; if (type_id >= bin->header.types_size ) { return NULL; } return_type = getstr (bin, bin->types[type_id].descriptor_id); if (!return_type) { return NULL; } if (!params_off) { return r_str_newf ("()%s", return_type);; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX again list_size is user controlled huge loop for (i = 0; i < list_size; i++) { int buff_len = 0; if (params_off + 4 + (i * 2) >= bin->size) { break; } type_idx = r_read_le16 (bufptr + params_off + 4 + (i * 2)); if (type_idx < 0 || type_idx >= bin->header.types_size || type_idx >= bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } buff_len = strlen (buff); size += buff_len + 1; signature = realloc (signature, size); strcpy (signature + pos, buff); pos += buff_len; signature[pos] = '\0'; } r = r_str_newf ("(%s)%s", signature, return_type); free (buff); free (signature); return r; } static RList *dex_method_signature2(RBinDexObj *bin, int method_idx) { ut32 proto_id, params_off, list_size; char *buff = NULL; ut8 *bufptr; ut16 type_idx; int i; RList *params = r_list_newf (free); if (!params) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { goto out_error; } proto_id = bin->methods[method_idx].proto_id; if (proto_id >= bin->header.prototypes_size) { goto out_error; } params_off = bin->protos[proto_id].parameters_off; if (params_off >= bin->size) { goto out_error; } if (!params_off) { return params; } bufptr = bin->b->buf; // size of the list, in entries list_size = r_read_le32 (bufptr + params_off); //XXX list_size tainted it may produce huge loop for (i = 0; i < list_size; i++) { ut64 of = params_off + 4 + (i * 2); if (of >= bin->size || of < params_off) { break; } type_idx = r_read_le16 (bufptr + of); if (type_idx >= bin->header.types_size || type_idx > bin->size) { break; } buff = getstr (bin, bin->types[type_idx].descriptor_id); if (!buff) { break; } r_list_append (params, buff); } return params; out_error: r_list_free (params); return NULL; } // TODO: fix this, now has more registers that it should // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L312 // https://github.com/android/platform_dalvik/blob/0641c2b4836fae3ee8daf6c0af45c316c84d5aeb/libdex/DexDebugInfo.cpp#L141 static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, &parameters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = "this"; debug_locals[argReg].descriptor = r_str_newf("%s;", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, &param_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, &register_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, &register_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf (" positions :\n"); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf (" 0x%04llx line=%llu\n", position->address, position->line); } rbin->cb_printf (" locals :\n"); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s\n", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s " "%s\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( " 0x%04x - 0x%04x reg=%d %s %s" "\n", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); } static int check (RBinFile *arch); static int check_bytes (const ut8 *buf, ut64 length); static Sdb *get_sdb (RBinObject *o) { if (!o || !o->bin_obj) { return NULL; } struct r_bin_dex_obj_t *bin = (struct r_bin_dex_obj_t *) o->bin_obj; if (bin->kv) { return bin->kv; } return NULL; } static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb){ void *res = NULL; RBuffer *tbuf = NULL; if (!buf || !sz || sz == UT64_MAX) { return NULL; } tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); res = r_bin_dex_new_buf (tbuf); r_buf_free (tbuf); return res; } static int load(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; if (!arch || !arch->o) { return false; } arch->o->bin_obj = load_bytes (arch, bytes, sz, arch->o->loadaddr, arch->sdb); return arch->o->bin_obj ? true: false; } static ut64 baddr(RBinFile *arch) { return 0; } static int check(RBinFile *arch) { const ut8 *bytes = arch ? r_buf_buffer (arch->buf) : NULL; ut64 sz = arch ? r_buf_size (arch->buf): 0; return check_bytes (bytes, sz); } static int check_bytes(const ut8 *buf, ut64 length) { if (!buf || length < 8) { return false; } // Non-extended opcode dex file if (!memcmp (buf, "dex\n035\0", 8)) { return true; } // Extended (jumnbo) opcode dex file, ICS+ only (sdk level 14+) if (!memcmp (buf, "dex\n036\0", 8)) { return true; } // M3 (Nov-Dec 07) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // M5 (Feb-Mar 08) if (!memcmp (buf, "dex\n009\0", 8)) { return true; } // Default fall through, should still be a dex file if (!memcmp (buf, "dex\n", 4)) { return true; } return false; } static RBinInfo *info(RBinFile *arch) { RBinHash *h; RBinInfo *ret = R_NEW0 (RBinInfo); if (!ret) { return NULL; } ret->file = arch->file? strdup (arch->file): NULL; ret->type = strdup ("DEX CLASS"); ret->has_va = false; ret->bclass = r_bin_dex_get_version (arch->o->bin_obj); ret->rclass = strdup ("class"); ret->os = strdup ("linux"); ret->subsystem = strdup ("any"); ret->machine = strdup ("Dalvik VM"); h = &ret->sum[0]; h->type = "sha1"; h->len = 20; h->addr = 12; h->from = 12; h->to = arch->buf->length-32; memcpy (h->buf, arch->buf->buf+12, 20); h = &ret->sum[1]; h->type = "adler32"; h->len = 4; h->addr = 0x8; h->from = 12; h->to = arch->buf->length-h->from; h = &ret->sum[2]; h->type = 0; memcpy (h->buf, arch->buf->buf + 8, 4); { ut32 *fc = (ut32 *)(arch->buf->buf + 8); ut32 cc = __adler32 (arch->buf->buf + 12, arch->buf->length - 12); if (*fc != cc) { eprintf ("# adler32 checksum doesn't match. Type this to fix it:\n"); eprintf ("wx `#sha1 $s-32 @32` @12 ; wx `#adler32 $s-12 @12` @8\n"); } } ret->arch = strdup ("dalvik"); ret->lang = "dalvik"; ret->bits = 32; ret->big_endian = 0; ret->dbg_info = 0; //1 | 4 | 8; /* Stripped | LineNums | Syms */ return ret; } static RList *strings(RBinFile *arch) { struct r_bin_dex_obj_t *bin = NULL; RBinString *ptr = NULL; RList *ret = NULL; int i, len; ut8 buf[6]; ut64 off; if (!arch || !arch->o) { return NULL; } bin = (struct r_bin_dex_obj_t *) arch->o->bin_obj; if (!bin || !bin->strings) { return NULL; } if (bin->header.strings_size > bin->size) { bin->strings = NULL; return NULL; } if (!(ret = r_list_newf (free))) { return NULL; } for (i = 0; i < bin->header.strings_size; i++) { if (!(ptr = R_NEW0 (RBinString))) { break; } if (bin->strings[i] > bin->size || bin->strings[i] + 6 > bin->size) { goto out_error; } r_buf_read_at (bin->b, bin->strings[i], (ut8*)&buf, 6); len = dex_read_uleb128 (buf); if (len > 1 && len < R_BIN_SIZEOF_STRINGS) { ptr->string = malloc (len + 1); if (!ptr->string) { goto out_error; } off = bin->strings[i] + dex_uleb128_len (buf); if (off + len >= bin->size || off + len < len) { free (ptr->string); goto out_error; } r_buf_read_at (bin->b, off, (ut8*)ptr->string, len); ptr->string[len] = 0; ptr->vaddr = ptr->paddr = bin->strings[i]; ptr->size = len; ptr->length = len; ptr->ordinal = i+1; r_list_append (ret, ptr); } else { free (ptr); } } return ret; out_error: r_list_free (ret); free (ptr); return NULL; } static char *dex_method_name(RBinDexObj *bin, int idx) { if (idx < 0 || idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[idx].class_id; if (cid < 0 || cid >= bin->header.strings_size) { return NULL; } int tid = bin->methods[idx].name_id; if (tid < 0 || tid >= bin->header.strings_size) { return NULL; } return getstr (bin, tid); } static char *dex_class_name_byid(RBinDexObj *bin, int cid) { int tid; if (!bin || !bin->types) { return NULL; } if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static char *dex_class_name(RBinDexObj *bin, RBinDexClass *c) { return dex_class_name_byid (bin, c->class_id); } static char *dex_field_name(RBinDexObj *bin, int fid) { int cid, tid, type_id; if (!bin || !bin->fields) { return NULL; } if (fid < 0 || fid >= bin->header.fields_size) { return NULL; } cid = bin->fields[fid].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } type_id = bin->fields[fid].type_id; if (type_id < 0 || type_id >= bin->header.types_size) { return NULL; } tid = bin->fields[fid].name_id; return r_str_newf ("%s->%s %s", getstr (bin, bin->types[cid].descriptor_id), getstr (bin, tid), getstr (bin, bin->types[type_id].descriptor_id)); } static char *dex_method_fullname(RBinDexObj *bin, int method_idx) { if (!bin || !bin->types) { return NULL; } if (method_idx < 0 || method_idx >= bin->header.method_size) { return NULL; } int cid = bin->methods[method_idx].class_id; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } char *name = dex_method_name (bin, method_idx); char *class_name = dex_class_name_byid (bin, cid); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func char *signature = dex_method_signature (bin, method_idx); char *flagname = r_str_newf ("%s.%s%s", class_name, name, signature); free (name); free (class_name); free (signature); return flagname; } static ut64 dex_get_type_offset(RBinFile *arch, int type_idx) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin || !bin->types) { return 0; } if (type_idx < 0 || type_idx >= bin->header.types_size) { return 0; } return bin->header.types_offset + type_idx * 0x04; //&bin->types[type_idx]; } static void __r_bin_class_free(RBinClass *p) { r_list_free (p->methods); r_list_free (p->fields); r_bin_class_free (p); } static char *dex_class_super_name(RBinDexObj *bin, RBinDexClass *c) { int cid, tid; if (!bin || !c || !bin->types) { return NULL; } cid = c->super_class; if (cid < 0 || cid >= bin->header.types_size) { return NULL; } tid = bin->types[cid].descriptor_id; return getstr (bin, tid); } static const ut8 *parse_dex_class_fields(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 fields_count, bool is_sfield) { struct r_bin_t *rbin = binfile->rbin; ut64 lastIndex = 0; ut8 ff[sizeof (DexField)] = {0}; int total, i, tid; DexField field; const char* type_str; for (i = 0; i < fields_count; i++) { ut64 fieldIndex, accessFlags; p = r_uleb128 (p, p_end - p, &fieldIndex); // fieldIndex p = r_uleb128 (p, p_end - p, &accessFlags); // accessFlags fieldIndex += lastIndex; total = bin->header.fields_offset + (sizeof (DexField) * fieldIndex); if (total >= bin->size || total < bin->header.fields_offset) { break; } if (r_buf_read_at (binfile->buf, total, ff, sizeof (DexField)) != sizeof (DexField)) { break; } field.class_id = r_read_le16 (ff); field.type_id = r_read_le16 (ff + 2); field.name_id = r_read_le32 (ff + 4); char *fieldName = getstr (bin, field.name_id); if (field.type_id >= bin->header.types_size) { break; } tid = bin->types[field.type_id].descriptor_id; type_str = getstr (bin, tid); RBinSymbol *sym = R_NEW0 (RBinSymbol); if (is_sfield) { sym->name = r_str_newf ("%s.sfield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("STATIC"); } else { sym->name = r_str_newf ("%s.ifield_%s:%s", cls->name, fieldName, type_str); sym->type = r_str_const ("FIELD"); } sym->name = r_str_replace (sym->name, "method.", "", 0); //sym->name = r_str_replace (sym->name, ";", "", 0); sym->paddr = sym->vaddr = total; sym->ordinal = (*sym_count)++; if (dexdump) { const char *accessStr = createAccessFlagStr ( accessFlags, kAccessForField); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", fieldName); rbin->cb_printf (" type : '%s'\n", type_str); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)accessFlags, accessStr); } r_list_append (bin->methods_list, sym); r_list_append (cls->fields, sym); lastIndex = fieldIndex; } return p; } // TODO: refactor this method // XXX it needs a lot of love!!! static const ut8 *parse_dex_class_method(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, RBinClass *cls, const ut8 *p, const ut8 *p_end, int *sym_count, ut64 DM, int *methods, bool is_direct) { struct r_bin_t *rbin = binfile->rbin; ut8 ff2[16] = {0}; ut8 ff3[8] = {0}; int i; ut64 omi = 0; bool catchAll; ut16 regsz, ins_size, outs_size, tries_size; ut16 handler_off, start_addr, insn_count; ut32 debug_info_off, insns_size; const ut8 *encoded_method_addr; for (i = 0; i < DM; i++) { encoded_method_addr = p; char *method_name, *flag_name; ut64 MI, MA, MC; p = r_uleb128 (p, p_end - p, &MI); MI += omi; omi = MI; p = r_uleb128 (p, p_end - p, &MA); p = r_uleb128 (p, p_end - p, &MC); // TODO: MOVE CHECKS OUTSIDE! if (MI < bin->header.method_size) { if (methods) { methods[MI] = 1; } } method_name = dex_method_name (bin, MI); char *signature = dex_method_signature (bin, MI); if (!method_name) { method_name = strdup ("unknown"); } flag_name = r_str_newf ("%s.method.%s%s", cls->name, method_name, signature); if (!flag_name) { R_FREE (method_name); R_FREE (signature); continue; } // TODO: check size // ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; ut64 v2, handler_type, handler_addr; int t; if (MC > 0) { // TODO: parse debug info // XXX why binfile->buf->base??? if (MC + 16 >= bin->size || MC + 16 < MC) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (method_name); R_FREE (flag_name); R_FREE (signature); continue; } regsz = r_read_le16 (ff2); ins_size = r_read_le16 (ff2 + 2); outs_size = r_read_le16 (ff2 + 4); tries_size = r_read_le16 (ff2 + 6); debug_info_off = r_read_le32 (ff2 + 8); insns_size = r_read_le32 (ff2 + 12); int padd = 0; if (tries_size > 0 && insns_size % 2) { padd = 2; } t = 16 + 2 * insns_size + padd; } if (dexdump) { const char* accessStr = createAccessFlagStr (MA, kAccessForMethod); rbin->cb_printf (" #%d : (in %s;)\n", i, cls->name); rbin->cb_printf (" name : '%s'\n", method_name); rbin->cb_printf (" type : '%s'\n", signature); rbin->cb_printf (" access : 0x%04x (%s)\n", (unsigned int)MA, accessStr); } if (MC > 0) { if (dexdump) { rbin->cb_printf (" code -\n"); rbin->cb_printf (" registers : %d\n", regsz); rbin->cb_printf (" ins : %d\n", ins_size); rbin->cb_printf (" outs : %d\n", outs_size); rbin->cb_printf ( " insns size : %d 16-bit code " "units\n", insns_size); } if (tries_size > 0) { if (dexdump) { rbin->cb_printf (" catches : %d\n", tries_size); } int j, m = 0; //XXX bucle controlled by tainted variable it could produces huge loop for (j = 0; j < tries_size; ++j) { ut64 offset = MC + t + j * 8; if (offset >= bin->size || offset < MC) { R_FREE (signature); break; } if (r_buf_read_at ( binfile->buf, binfile->buf->base + offset, ff3, 8) < 1) { // free (method_name); R_FREE (signature); break; } start_addr = r_read_le32 (ff3); insn_count = r_read_le16 (ff3 + 4); handler_off = r_read_le16 (ff3 + 6); char* s = NULL; if (dexdump) { rbin->cb_printf ( " 0x%04x - " "0x%04x\n", start_addr, (start_addr + insn_count)); } const ut8 *p3, *p3_end; //XXX tries_size is tainted and oob here int off = MC + t + tries_size * 8 + handler_off; if (off >= bin->size || off < tries_size) { R_FREE (signature); break; } p3 = r_buf_get_at (binfile->buf, off, NULL); p3_end = p3 + binfile->buf->length - off; st64 size = r_sleb128 (&p3, p3_end); if (size <= 0) { catchAll = true; size = -size; } else { catchAll = false; } for (m = 0; m < size; m++) { p3 = r_uleb128 (p3, p3_end - p3, &handler_type); p3 = r_uleb128 (p3, p3_end - p3, &handler_addr); if (handler_type > 0 && handler_type < bin->header.types_size) { s = getstr (bin, bin->types[handler_type].descriptor_id); if (dexdump) { rbin->cb_printf ( " %s " "-> 0x%04llx\n", s, handler_addr); } } else { if (dexdump) { rbin->cb_printf ( " " "(error) -> " "0x%04llx\n", handler_addr); } } } if (catchAll) { p3 = r_uleb128 (p3, p3_end - p3, &v2); if (dexdump) { rbin->cb_printf ( " " "<any> -> " "0x%04llx\n", v2); } } } } else { if (dexdump) { rbin->cb_printf ( " catches : " "(none)\n"); } } } else { if (dexdump) { rbin->cb_printf ( " code : (none)\n"); } } if (*flag_name) { RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = flag_name; // is_direct is no longer used // if method has code *addr points to code // otherwise it points to the encoded method if (MC > 0) { sym->type = r_str_const ("FUNC"); sym->paddr = MC;// + 0x10; sym->vaddr = MC;// + 0x10; } else { sym->type = r_str_const ("METH"); sym->paddr = encoded_method_addr - binfile->buf->buf; sym->vaddr = encoded_method_addr - binfile->buf->buf; } if ((MA & 0x1) == 0x1) { sym->bind = r_str_const ("GLOBAL"); } else { sym->bind = r_str_const ("LOCAL"); } sym->ordinal = (*sym_count)++; if (MC > 0) { if (r_buf_read_at (binfile->buf, binfile->buf->base + MC, ff2, 16) < 1) { R_FREE (sym); R_FREE (signature); continue; } //ut16 regsz = r_read_le16 (ff2); //ut16 ins_size = r_read_le16 (ff2 + 2); //ut16 outs_size = r_read_le16 (ff2 + 4); ut16 tries_size = r_read_le16 (ff2 + 6); //ut32 debug_info_off = r_read_le32 (ff2 + 8); ut32 insns_size = r_read_le32 (ff2 + 12); ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; if (tries_size > 0) { //prolog_size += 2 + 8*tries_size; // we need to parse all so the catch info... } // TODO: prolog_size sym->paddr = MC + prolog_size;// + 0x10; sym->vaddr = MC + prolog_size;// + 0x10; //if (is_direct) { sym->size = insns_size * 2; //} //eprintf("%s (0x%x-0x%x) size=%d\nregsz=%d\ninsns_size=%d\nouts_size=%d\ntries_size=%d\ninsns_size=%d\n", flag_name, sym->vaddr, sym->vaddr+sym->size, prolog_size, regsz, ins_size, outs_size, tries_size, insns_size); r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); if (bin->code_from > sym->paddr) { bin->code_from = sym->paddr; } if (bin->code_to < sym->paddr) { bin->code_to = sym->paddr; } if (!mdb) { mdb = sdb_new0 (); } sdb_num_set (mdb, sdb_fmt (0, "method.%d", MI), sym->paddr, 0); // ----------------- // WORK IN PROGRESS // ----------------- if (0) { if (MA & 0x10000) { //ACC_CONSTRUCTOR if (!cdb) { cdb = sdb_new0 (); } sdb_num_set (cdb, sdb_fmt (0, "%d", c->class_id), sym->paddr, 0); } } } else { sym->size = 0; r_list_append (bin->methods_list, sym); r_list_append (cls->methods, sym); } if (MC > 0 && debug_info_off > 0 && bin->header.data_offset < debug_info_off && debug_info_off < bin->header.data_offset + bin->header.data_size) { dex_parse_debug_item (binfile, bin, c, MI, MA, sym->paddr, ins_size, insns_size, cls->name, regsz, debug_info_off); } else if (MC > 0) { if (dexdump) { rbin->cb_printf (" positions :\n"); rbin->cb_printf (" locals :\n"); } } } else { R_FREE (flag_name); } R_FREE (signature); R_FREE (method_name); } return p; } static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf (" Class descriptor : '%s;'\n", class_name); rbin->cb_printf ( " Access flags : 0x%04x (%s)\n", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf (" Superclass : '%s'\n", dex_class_super_name (bin, c)); rbin->cb_printf (" Interfaces -\n"); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32 (p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( " #%d : '%s'\n", z, getstr (bin, tid)); } } } } // TODO: this is quite ugly if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( " Static fields -\n Instance fields " "-\n Direct methods -\n Virtual methods " "-\n"); } } else { // TODO: move to func, def or inline // class_data_offset => [class_offset, class_defs_off+class_defs_size*32] if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; //XXX check for NULL!! c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf (" Static fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf (" Instance fields -\n"); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf (" Direct methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf (" Virtual methods -\n"); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( " source_file_idx : %d (unknown)\n\n", c->source_file); } else { rbin->cb_printf (" source_file_idx : %d (%s)\n\n", c->source_file, source_file); } } // TODO:!!!! // FIX: FREE BEFORE ALLOCATE!!! //free (class_name); } static bool is_class_idx_in_code_classes(RBinDexObj *bin, int class_idx) { int i; for (i = 0; i < bin->header.class_size; i++) { if (class_idx == bin->classes[i].class_id) { return true; } } return false; } static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; // doublecheck?? if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); // TODO: is this posible after R_MIN ?? if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); //XXX so damn unsafe check buffer boundaries!!!! //XXX use r_buf API!! sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; } static RList* imports(RBinFile *arch) { RBinDexObj *bin = (RBinDexObj*) arch->o->bin_obj; if (!bin) { return NULL; } if (bin && bin->imports_list) { return bin->imports_list; } dex_loadcode (arch, bin); return bin->imports_list; } static RList *methods(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->methods_list) { dex_loadcode (arch, bin); } return bin->methods_list; } static RList *classes(RBinFile *arch) { RBinDexObj *bin; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; if (!bin->classes_list) { dex_loadcode (arch, bin); } return bin->classes_list; } static bool already_entry(RList *entries, ut64 vaddr) { RBinAddr *e; RListIter *iter; r_list_foreach (entries, iter, e) { if (e->vaddr == vaddr) { return true; } } return false; } static RList *entries(RBinFile *arch) { RListIter *iter; RBinDexObj *bin; RBinSymbol *m; RBinAddr *ptr; RList *ret; if (!arch || !arch->o || !arch->o->bin_obj) { return NULL; } bin = (RBinDexObj*) arch->o->bin_obj; ret = r_list_newf ((RListFree)free); if (!bin->methods_list) { dex_loadcode (arch, bin); } // STEP 1. ".onCreate(Landroid/os/Bundle;)V" r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 30 && m->bind && !strcmp(m->bind, "GLOBAL") && !strcmp (m->name + strlen (m->name) - 31, ".onCreate(Landroid/os/Bundle;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } // STEP 2. ".main([Ljava/lang/String;)V" if (r_list_empty (ret)) { r_list_foreach (bin->methods_list, iter, m) { if (strlen (m->name) > 26 && !strcmp (m->name + strlen (m->name) - 27, ".main([Ljava/lang/String;)V")) { if (!already_entry (ret, m->paddr)) { if ((ptr = R_NEW0 (RBinAddr))) { ptr->paddr = ptr->vaddr = m->paddr; r_list_append (ret, ptr); } } } } } // STEP 3. NOTHING FOUND POINT TO CODE_INIT if (r_list_empty (ret)) { if (!already_entry (ret, bin->code_from)) { ptr = R_NEW0 (RBinAddr); if (ptr) { ptr->paddr = ptr->vaddr = bin->code_from; r_list_append (ret, ptr); } } } return ret; } static ut64 offset_of_method_idx(RBinFile *arch, struct r_bin_dex_obj_t *dex, int idx) { ut64 off = dex->header.method_offset + idx; off = sdb_num_get (mdb, sdb_fmt (0, "method.%d", idx), 0); return (ut64) off; } // TODO: change all return type for all getoffset static int getoffset(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods // TODO: ADD CHECK return offset_of_method_idx (arch, dex, idx); case 'o': // objects break; case 's': // strings if (dex->header.strings_size > idx) { if (dex->strings) return dex->strings[idx]; } break; case 't': // type return dex_get_type_offset (arch, idx); case 'c': // class return dex_get_type_offset (arch, idx); //return sdb_num_get (cdb, sdb_fmt (0, "%d", idx), 0); } return -1; } static char *getname(RBinFile *arch, int type, int idx) { struct r_bin_dex_obj_t *dex = arch->o->bin_obj; switch (type) { case 'm': // methods return dex_method_fullname (dex, idx); case 'c': // classes return dex_class_name_byid (dex, idx); case 'f': // fields return dex_field_name (dex, idx); } return NULL; } static RList *sections(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; RList *ml = methods (arch); RBinSection *ptr = NULL; int ns, fsymsz = 0; RList *ret = NULL; RListIter *iter; RBinSymbol *m; int fsym = 0; r_list_foreach (ml, iter, m) { if (!fsym || m->paddr < fsym) { fsym = m->paddr; } ns = m->paddr + m->size; if (ns > arch->buf->length) { continue; } if (ns > fsymsz) { fsymsz = ns; } } if (!fsym) { return NULL; } if (!(ret = r_list_new ())) { return NULL; } ret->free = free; if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "header"); ptr->size = ptr->vsize = sizeof (struct dex_header_t); ptr->paddr= ptr->vaddr = 0; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "constpool"); //ptr->size = ptr->vsize = fsym; ptr->paddr= ptr->vaddr = sizeof (struct dex_header_t); ptr->size = bin->code_from - ptr->vaddr; // fix size ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { strcpy (ptr->name, "code"); ptr->vaddr = ptr->paddr = bin->code_from; //ptr->vaddr = fsym; ptr->size = bin->code_to - ptr->paddr; ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE | R_BIN_SCN_MAP; ptr->add = true; r_list_append (ret, ptr); } if ((ptr = R_NEW0 (RBinSection))) { //ut64 sz = arch ? r_buf_size (arch->buf): 0; strcpy (ptr->name, "data"); ptr->paddr = ptr->vaddr = fsymsz+fsym; if (ptr->vaddr > arch->buf->length) { ptr->paddr = ptr->vaddr = bin->code_to; ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; } else { ptr->size = ptr->vsize = arch->buf->length - ptr->vaddr; // hacky workaround //dprintf ("Hack\n"); //ptr->size = ptr->vsize = 1024; } ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_MAP; //|2; ptr->add = true; r_list_append (ret, ptr); } return ret; } static void header(RBinFile *arch) { struct r_bin_dex_obj_t *bin = arch->o->bin_obj; struct r_bin_t *rbin = arch->rbin; rbin->cb_printf ("DEX file header:\n"); rbin->cb_printf ("magic : 'dex\\n035\\0'\n"); rbin->cb_printf ("checksum : %x\n", bin->header.checksum); rbin->cb_printf ("signature : %02x%02x...%02x%02x\n", bin->header.signature[0], bin->header.signature[1], bin->header.signature[18], bin->header.signature[19]); rbin->cb_printf ("file_size : %d\n", bin->header.size); rbin->cb_printf ("header_size : %d\n", bin->header.header_size); rbin->cb_printf ("link_size : %d\n", bin->header.linksection_size); rbin->cb_printf ("link_off : %d (0x%06x)\n", bin->header.linksection_offset, bin->header.linksection_offset); rbin->cb_printf ("string_ids_size : %d\n", bin->header.strings_size); rbin->cb_printf ("string_ids_off : %d (0x%06x)\n", bin->header.strings_offset, bin->header.strings_offset); rbin->cb_printf ("type_ids_size : %d\n", bin->header.types_size); rbin->cb_printf ("type_ids_off : %d (0x%06x)\n", bin->header.types_offset, bin->header.types_offset); rbin->cb_printf ("proto_ids_size : %d\n", bin->header.prototypes_size); rbin->cb_printf ("proto_ids_off : %d (0x%06x)\n", bin->header.prototypes_offset, bin->header.prototypes_offset); rbin->cb_printf ("field_ids_size : %d\n", bin->header.fields_size); rbin->cb_printf ("field_ids_off : %d (0x%06x)\n", bin->header.fields_offset, bin->header.fields_offset); rbin->cb_printf ("method_ids_size : %d\n", bin->header.method_size); rbin->cb_printf ("method_ids_off : %d (0x%06x)\n", bin->header.method_offset, bin->header.method_offset); rbin->cb_printf ("class_defs_size : %d\n", bin->header.class_size); rbin->cb_printf ("class_defs_off : %d (0x%06x)\n", bin->header.class_offset, bin->header.class_offset); rbin->cb_printf ("data_size : %d\n", bin->header.data_size); rbin->cb_printf ("data_off : %d (0x%06x)\n\n", bin->header.data_offset, bin->header.data_offset); // TODO: print information stored in the RBIN not this ugly fix dexdump = true; bin->methods_list = NULL; dex_loadcode (arch, bin); dexdump = false; } static ut64 size(RBinFile *arch) { int ret; ut32 off = 0, len = 0; ut8 u32s[sizeof (ut32)] = {0}; ret = r_buf_read_at (arch->buf, 108, u32s, 4); if (ret != 4) { return 0; } off = r_read_le32 (u32s); ret = r_buf_read_at (arch->buf, 104, u32s, 4); if (ret != 4) { return 0; } len = r_read_le32 (u32s); return off + len; } RBinPlugin r_bin_plugin_dex = { .name = "dex", .desc = "dex format bin plugin", .license = "LGPL3", .get_sdb = &get_sdb, .load = &load, .load_bytes = &load_bytes, .check = &check, .check_bytes = &check_bytes, .baddr = &baddr, .entries = entries, .classes = classes, .sections = sections, .symbols = methods, .imports = imports, .strings = strings, .info = &info, .header = &header, .size = &size, .get_offset = &getoffset, .get_name = &getname, .dbginfo = &r_bin_dbginfo_dex, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_BIN, .data = &r_bin_plugin_dex, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_3181_0
crossvul-cpp_data_good_4901_1
/* * DBD::mysql - DBI driver for the mysql database * * Copyright (c) 2004-2014 Patrick Galbraith * Copyright (c) 2013-2014 Michiel Beijen * Copyright (c) 2004-2007 Alexey Stroganov * Copyright (c) 2003-2005 Rudolf Lippan * Copyright (c) 1997-2003 Jochen Wiedmann * * You may distribute this under the terms of either the GNU General Public * License or the Artistic License, as specified in the Perl README file. */ #ifdef WIN32 #include "windows.h" #include "winsock.h" #endif #include "dbdimp.h" #if defined(WIN32) && defined(WORD) #undef WORD typedef short WORD; #endif #ifdef WIN32 #define MIN min #else #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #endif #if MYSQL_ASYNC # include <poll.h> # include <errno.h> # define ASYNC_CHECK_RETURN(h, value)\ if(imp_dbh->async_query_in_flight) {\ do_error(h, 2000, "Calling a synchronous function on an asynchronous handle", "HY000");\ return (value);\ } #else # define ASYNC_CHECK_RETURN(h, value) #endif static int parse_number(char *string, STRLEN len, char **end); DBISTATE_DECLARE; typedef struct sql_type_info_s { const char *type_name; int data_type; int column_size; const char *literal_prefix; const char *literal_suffix; const char *create_params; int nullable; int case_sensitive; int searchable; int unsigned_attribute; int fixed_prec_scale; int auto_unique_value; const char *local_type_name; int minimum_scale; int maximum_scale; int num_prec_radix; int sql_datatype; int sql_datetime_sub; int interval_precision; int native_type; int is_num; } sql_type_info_t; /* This function manually counts the number of placeholders in an SQL statement, used for emulated prepare statements < 4.1.3 */ static int count_params(imp_xxh_t *imp_xxh, pTHX_ char *statement, bool bind_comment_placeholders) { bool comment_end= false; char* ptr= statement; int num_params= 0; int comment_length= 0; char c; if (DBIc_DBISTATE(imp_xxh)->debug >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">count_params statement %s\n", statement); while ( (c = *ptr++) ) { switch (c) { /* so, this is a -- comment, so let's burn up characters */ case '-': { if (bind_comment_placeholders) { c = *ptr++; break; } else { comment_length= 1; /* let's see if the next one is a dash */ c = *ptr++; if (c == '-') { /* if two dashes, ignore everything until newline */ while ((c = *ptr)) { if (DBIc_DBISTATE(imp_xxh)->debug >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c\n", c); ptr++; comment_length++; if (c == '\n') { comment_end= true; break; } } /* if not comment_end, the comment never ended and we need to iterate back to the beginning of where we started and let the database handle whatever is in the statement */ if (! comment_end) ptr-= comment_length; } /* otherwise, only one dash/hyphen, backtrack by one */ else ptr--; break; } } /* c-type comments */ case '/': { if (bind_comment_placeholders) { c = *ptr++; break; } else { c = *ptr++; /* let's check if the next one is an asterisk */ if (c == '*') { comment_length= 0; comment_end= false; /* ignore everything until closing comment */ while ((c= *ptr)) { ptr++; comment_length++; if (c == '*') { c = *ptr++; /* alas, end of comment */ if (c == '/') { comment_end= true; break; } /* nope, just an asterisk, not so fast, not end of comment, go back one */ else ptr--; } } /* if the end of the comment was never found, we have to backtrack to wherever we first started skipping over the possible comment. This means we will pass the statement to the database to see its own fate and issue the error */ if (!comment_end) ptr -= comment_length; } else ptr--; break; } } case '`': case '"': case '\'': /* Skip string */ { char end_token = c; while ((c = *ptr) && c != end_token) { if (c == '\\') if (! *(++ptr)) continue; ++ptr; } if (c) ++ptr; break; } case '?': ++num_params; break; default: break; } } return num_params; } /* allocate memory in statement handle per number of placeholders */ static imp_sth_ph_t *alloc_param(int num_params) { imp_sth_ph_t *params; if (num_params) Newz(908, params, (unsigned int) num_params, imp_sth_ph_t); else params= NULL; return params; } #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* allocate memory in MYSQL_BIND bind structure per number of placeholders */ static MYSQL_BIND *alloc_bind(int num_params) { MYSQL_BIND *bind; if (num_params) Newz(908, bind, (unsigned int) num_params, MYSQL_BIND); else bind= NULL; return bind; } /* allocate memory in fbind imp_sth_phb_t structure per number of placeholders */ static imp_sth_phb_t *alloc_fbind(int num_params) { imp_sth_phb_t *fbind; if (num_params) Newz(908, fbind, (unsigned int) num_params, imp_sth_phb_t); else fbind= NULL; return fbind; } /* alloc memory for imp_sth_fbh_t fbuffer per number of fields */ static imp_sth_fbh_t *alloc_fbuffer(int num_fields) { imp_sth_fbh_t *fbh; if (num_fields) Newz(908, fbh, (unsigned int) num_fields, imp_sth_fbh_t); else fbh= NULL; return fbh; } /* free MYSQL_BIND bind struct */ static void free_bind(MYSQL_BIND *bind) { if (bind) Safefree(bind); } /* free imp_sth_phb_t fbind structure */ static void free_fbind(imp_sth_phb_t *fbind) { if (fbind) Safefree(fbind); } /* free imp_sth_fbh_t fbh structure */ static void free_fbuffer(imp_sth_fbh_t *fbh) { if (fbh) Safefree(fbh); } #endif /* free statement param structure per num_params */ static void free_param(pTHX_ imp_sth_ph_t *params, int num_params) { if (params) { int i; for (i= 0; i < num_params; i++) { imp_sth_ph_t *ph= params+i; if (ph->value) { (void) SvREFCNT_dec(ph->value); ph->value= NULL; } } Safefree(params); } } /* Convert a MySQL type to a type that perl can handle NOTE: In the future we may want to return a struct with a lot of information for each type */ static enum enum_field_types mysql_to_perl_type(enum enum_field_types type) { static enum enum_field_types enum_type; switch (type) { case MYSQL_TYPE_DOUBLE: case MYSQL_TYPE_FLOAT: enum_type= MYSQL_TYPE_DOUBLE; break; case MYSQL_TYPE_SHORT: case MYSQL_TYPE_TINY: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_YEAR: #if IVSIZE >= 8 case MYSQL_TYPE_LONGLONG: #endif enum_type= MYSQL_TYPE_LONG; break; #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_BIT: enum_type= MYSQL_TYPE_BIT; break; #endif #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_NEWDECIMAL: #endif case MYSQL_TYPE_DECIMAL: enum_type= MYSQL_TYPE_DECIMAL; break; #if IVSIZE < 8 case MYSQL_TYPE_LONGLONG: #endif case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_VAR_STRING: #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_VARCHAR: #endif case MYSQL_TYPE_STRING: enum_type= MYSQL_TYPE_STRING; break; #if MYSQL_VERSION_ID > GEO_DATATYPE_VERSION case MYSQL_TYPE_GEOMETRY: #endif case MYSQL_TYPE_BLOB: case MYSQL_TYPE_TINY_BLOB: enum_type= MYSQL_TYPE_BLOB; break; default: enum_type= MYSQL_TYPE_STRING; /* MySQL can handle all types as strings */ } return(enum_type); } #if defined(DBD_MYSQL_EMBEDDED) /* count embedded options */ int count_embedded_options(char *st) { int rc; char c; char *ptr; ptr= st; rc= 0; if (st) { while ((c= *ptr++)) { if (c == ',') rc++; } rc++; } return rc; } /* Free embedded options */ int free_embedded_options(char ** options_list, int options_count) { int i; for (i= 0; i < options_count; i++) { if (options_list[i]) free(options_list[i]); } free(options_list); return 1; } /* Print out embedded option settings */ int print_embedded_options(PerlIO *stream, char ** options_list, int options_count) { int i; for (i=0; i<options_count; i++) { if (options_list[i]) PerlIO_printf(stream, "Embedded server, parameter[%d]=%s\n", i, options_list[i]); } return 1; } /* */ char **fill_out_embedded_options(PerlIO *stream, char *options, int options_type, int slen, int cnt) { int ind, len; char c; char *ptr; char **options_list= NULL; if (!(options_list= (char **) calloc(cnt, sizeof(char *)))) { PerlIO_printf(stream, "Initialize embedded server. Out of memory \n"); return NULL; } ptr= options; ind= 0; if (options_type == 0) { /* server_groups list NULL terminated */ options_list[cnt]= (char *) NULL; } if (options_type == 1) { /* first item in server_options list is ignored. fill it with \0 */ if (!(options_list[0]= calloc(1,sizeof(char)))) return NULL; ind++; } while ((c= *ptr++)) { slen--; if (c == ',' || !slen) { len= ptr - options; if (c == ',') len--; if (!(options_list[ind]=calloc(len+1,sizeof(char)))) return NULL; strncpy(options_list[ind], options, len); ind++; options= ptr; } } return options_list; } #endif /* constructs an SQL statement previously prepared with actual values replacing placeholders */ static char *parse_params( imp_xxh_t *imp_xxh, pTHX_ MYSQL *sock, char *statement, STRLEN *slen_ptr, imp_sth_ph_t* params, int num_params, bool bind_type_guessing, bool bind_comment_placeholders) { bool comment_end= false; char *salloc, *statement_ptr; char *statement_ptr_end, *ptr, *valbuf; char *cp, *end; int alen, i; int slen= *slen_ptr; int limit_flag= 0; int comment_length=0; STRLEN vallen; imp_sth_ph_t *ph; if (DBIc_DBISTATE(imp_xxh)->debug >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">parse_params statement %s\n", statement); if (num_params == 0) return NULL; while (isspace(*statement)) { ++statement; --slen; } /* Calculate the number of bytes being allocated for the statement */ alen= slen; for (i= 0, ph= params; i < num_params; i++, ph++) { int defined= 0; if (ph->value) { if (SvMAGICAL(ph->value)) mg_get(ph->value); if (SvOK(ph->value)) defined=1; } if (!defined) alen+= 3; /* Erase '?', insert 'NULL' */ else { valbuf= SvPV(ph->value, vallen); alen+= 2+vallen+1; /* this will most likely not happen since line 214 */ /* of mysql.xs hardcodes all types to SQL_VARCHAR */ if (!ph->type) { if (bind_type_guessing) { valbuf= SvPV(ph->value, vallen); ph->type= SQL_INTEGER; if (parse_number(valbuf, vallen, &end) != 0) { ph->type= SQL_VARCHAR; } } else ph->type= SQL_VARCHAR; } } } /* Allocate memory, why *2, well, because we have ptr and statement_ptr */ New(908, salloc, alen*2, char); ptr= salloc; i= 0; /* Now create the statement string; compare count_params above */ statement_ptr_end= (statement_ptr= statement)+ slen; while (statement_ptr < statement_ptr_end) { /* LIMIT should be the last part of the query, in most cases */ if (! limit_flag) { /* it would be good to be able to handle any number of cases and orders */ if ((*statement_ptr == 'l' || *statement_ptr == 'L') && (!strncmp(statement_ptr+1, "imit ?", 6) || !strncmp(statement_ptr+1, "IMIT ?", 6))) { limit_flag = 1; } } switch (*statement_ptr) { /* comment detection. Anything goes in a comment */ case '-': { if (bind_comment_placeholders) { *ptr++= *statement_ptr++; break; } else { comment_length= 1; comment_end= false; *ptr++ = *statement_ptr++; if (*statement_ptr == '-') { /* ignore everything until newline or end of string */ while (*statement_ptr) { comment_length++; *ptr++ = *statement_ptr++; if (!*statement_ptr || *statement_ptr == '\n') { comment_end= true; break; } } /* if not end of comment, go back to where we started, no end found */ if (! comment_end) { statement_ptr -= comment_length; ptr -= comment_length; } } break; } } /* c-type comments */ case '/': { if (bind_comment_placeholders) { *ptr++= *statement_ptr++; break; } else { comment_length= 1; comment_end= false; *ptr++ = *statement_ptr++; if (*statement_ptr == '*') { /* use up characters everything until newline */ while (*statement_ptr) { *ptr++ = *statement_ptr++; comment_length++; if (!strncmp(statement_ptr, "*/", 2)) { comment_length += 2; comment_end= true; break; } } /* Go back to where started if comment end not found */ if (! comment_end) { statement_ptr -= comment_length; ptr -= comment_length; } } break; } } case '`': case '\'': case '"': /* Skip string */ { char endToken = *statement_ptr++; *ptr++ = endToken; while (statement_ptr != statement_ptr_end && *statement_ptr != endToken) { if (*statement_ptr == '\\') { *ptr++ = *statement_ptr++; if (statement_ptr == statement_ptr_end) break; } *ptr++= *statement_ptr++; } if (statement_ptr != statement_ptr_end) *ptr++= *statement_ptr++; } break; case '?': /* Insert parameter */ statement_ptr++; if (i >= num_params) { break; } ph = params+ (i++); if (!ph->value || !SvOK(ph->value)) { *ptr++ = 'N'; *ptr++ = 'U'; *ptr++ = 'L'; *ptr++ = 'L'; } else { int is_num = FALSE; valbuf= SvPV(ph->value, vallen); if (valbuf) { switch (ph->type) { case SQL_NUMERIC: case SQL_DECIMAL: case SQL_INTEGER: case SQL_SMALLINT: case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE: case SQL_BIGINT: case SQL_TINYINT: is_num = TRUE; break; } /* (note this sets *end, which we use if is_num) */ if ( parse_number(valbuf, vallen, &end) != 0 && is_num) { if (bind_type_guessing) { /* .. not a number, so apparently we guessed wrong */ is_num = 0; ph->type = SQL_VARCHAR; } } /* we're at the end of the query, so any placeholders if */ /* after a LIMIT clause will be numbers and should not be quoted */ if (limit_flag == 1) is_num = TRUE; if (!is_num) { *ptr++ = '\''; ptr += mysql_real_escape_string(sock, ptr, valbuf, vallen); *ptr++ = '\''; } else { for (cp= valbuf; cp < end; cp++) *ptr++= *cp; } } } break; /* in case this is a nested LIMIT */ case ')': limit_flag = 0; *ptr++ = *statement_ptr++; break; default: *ptr++ = *statement_ptr++; break; } } *slen_ptr = ptr - salloc; *ptr++ = '\0'; return(salloc); } int bind_param(imp_sth_ph_t *ph, SV *value, IV sql_type) { dTHX; if (ph->value) { if (SvMAGICAL(ph->value)) mg_get(ph->value); (void) SvREFCNT_dec(ph->value); } ph->value= newSVsv(value); if (sql_type) ph->type = sql_type; return TRUE; } static const sql_type_info_t SQL_GET_TYPE_INFO_values[]= { { "varchar", SQL_VARCHAR, 255, "'", "'", "max length", 1, 0, 3, 0, 0, 0, "variable length string", 0, 0, 0, SQL_VARCHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_VAR_STRING, 0, #else MYSQL_TYPE_STRING, 0, #endif }, { "decimal", SQL_DECIMAL, 15, NULL, NULL, "precision,scale", 1, 0, 3, 0, 0, 0, "double", 0, 6, 2, SQL_DECIMAL, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DECIMAL, 1 #else MYSQL_TYPE_DECIMAL, 1 #endif }, { "tinyint", SQL_TINYINT, 3, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Tiny integer", 0, 0, 10, SQL_TINYINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TINY, 1 #else MYSQL_TYPE_TINY, 1 #endif }, { "smallint", SQL_SMALLINT, 5, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Short integer", 0, 0, 10, SQL_SMALLINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_SHORT, 1 #else MYSQL_TYPE_SHORT, 1 #endif }, { "integer", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "float", SQL_REAL, 7, NULL, NULL, NULL, 1, 0, 0, 0, 0, 0, "float", 0, 2, 10, SQL_FLOAT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_FLOAT, 1 #else MYSQL_TYPE_FLOAT, 1 #endif }, { "double", SQL_FLOAT, 15, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "double", 0, 4, 2, SQL_FLOAT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DOUBLE, 1 #else MYSQL_TYPE_DOUBLE, 1 #endif }, { "double", SQL_DOUBLE, 15, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "double", 0, 4, 10, SQL_DOUBLE, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DOUBLE, 1 #else MYSQL_TYPE_DOUBLE, 1 #endif }, /* FIELD_TYPE_NULL ? */ { "timestamp", SQL_TIMESTAMP, 14, "'", "'", NULL, 0, 0, 3, 0, 0, 0, "timestamp", 0, 0, 0, SQL_TIMESTAMP, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TIMESTAMP, 0 #else MYSQL_TYPE_TIMESTAMP, 0 #endif }, { "bigint", SQL_BIGINT, 19, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Longlong integer", 0, 0, 10, SQL_BIGINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONGLONG, 1 #else MYSQL_TYPE_LONGLONG, 1 #endif }, { "mediumint", SQL_INTEGER, 8, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Medium integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_INT24, 1 #else MYSQL_TYPE_INT24, 1 #endif }, { "date", SQL_DATE, 10, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "date", 0, 0, 0, SQL_DATE, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DATE, 0 #else MYSQL_TYPE_DATE, 0 #endif }, { "time", SQL_TIME, 6, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "time", 0, 0, 0, SQL_TIME, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TIME, 0 #else MYSQL_TYPE_TIME, 0 #endif }, { "datetime", SQL_TIMESTAMP, 21, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "datetime", 0, 0, 0, SQL_TIMESTAMP, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DATETIME, 0 #else MYSQL_TYPE_DATETIME, 0 #endif }, { "year", SQL_SMALLINT, 4, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "year", 0, 0, 10, SQL_SMALLINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_YEAR, 0 #else MYSQL_TYPE_YEAR, 0 #endif }, { "date", SQL_DATE, 10, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "date", 0, 0, 0, SQL_DATE, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_NEWDATE, 0 #else MYSQL_TYPE_NEWDATE, 0 #endif }, { "enum", SQL_VARCHAR, 255, "'", "'", NULL, 1, 0, 1, 0, 0, 0, "enum(value1,value2,value3...)", 0, 0, 0, 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_ENUM, 0 #else MYSQL_TYPE_ENUM, 0 #endif }, { "set", SQL_VARCHAR, 255, "'", "'", NULL, 1, 0, 1, 0, 0, 0, "set(value1,value2,value3...)", 0, 0, 0, 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_SET, 0 #else MYSQL_TYPE_SET, 0 #endif }, { "blob", SQL_LONGVARBINARY, 65535, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object (0-65535)", 0, 0, 0, SQL_LONGVARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_BLOB, 0 #else MYSQL_TYPE_BLOB, 0 #endif }, { "tinyblob", SQL_VARBINARY, 255, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object (0-255) ", 0, 0, 0, SQL_VARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TINY_BLOB, 0 #else FIELD_TYPE_TINY_BLOB, 0 #endif }, { "mediumblob", SQL_LONGVARBINARY, 16777215, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object", 0, 0, 0, SQL_LONGVARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_MEDIUM_BLOB, 0 #else MYSQL_TYPE_MEDIUM_BLOB, 0 #endif }, { "longblob", SQL_LONGVARBINARY, 2147483647, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "binary large object, use mediumblob instead", 0, 0, 0, SQL_LONGVARBINARY, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG_BLOB, 0 #else MYSQL_TYPE_LONG_BLOB, 0 #endif }, { "char", SQL_CHAR, 255, "'", "'", "max length", 1, 0, 3, 0, 0, 0, "string", 0, 0, 0, SQL_CHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_STRING, 0 #else MYSQL_TYPE_STRING, 0 #endif }, { "decimal", SQL_NUMERIC, 15, NULL, NULL, "precision,scale", 1, 0, 3, 0, 0, 0, "double", 0, 6, 2, SQL_NUMERIC, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_DECIMAL, 1 #else MYSQL_TYPE_DECIMAL, 1 #endif }, { "tinyint unsigned", SQL_TINYINT, 3, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Tiny integer unsigned", 0, 0, 10, SQL_TINYINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_TINY, 1 #else MYSQL_TYPE_TINY, 1 #endif }, { "smallint unsigned", SQL_SMALLINT, 5, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Short integer unsigned", 0, 0, 10, SQL_SMALLINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_SHORT, 1 #else MYSQL_TYPE_SHORT, 1 #endif }, { "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Medium integer unsigned", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_INT24, 1 #else MYSQL_TYPE_INT24, 1 #endif }, { "int unsigned", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "integer unsigned", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "int", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "integer unsigned", SQL_INTEGER, 10, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "integer", 0, 0, 10, SQL_INTEGER, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONG, 1 #else MYSQL_TYPE_LONG, 1 #endif }, { "bigint unsigned", SQL_BIGINT, 20, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Longlong integer unsigned", 0, 0, 10, SQL_BIGINT, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_LONGLONG, 1 #else MYSQL_TYPE_LONGLONG, 1 #endif }, { "text", SQL_LONGVARCHAR, 65535, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "large text object (0-65535)", 0, 0, 0, SQL_LONGVARCHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_BLOB, 0 #else MYSQL_TYPE_BLOB, 0 #endif }, { "mediumtext", SQL_LONGVARCHAR, 16777215, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "large text object", 0, 0, 0, SQL_LONGVARCHAR, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 FIELD_TYPE_MEDIUM_BLOB, 0 #else MYSQL_TYPE_MEDIUM_BLOB, 0 #endif }, { "mediumint unsigned auto_increment", SQL_INTEGER, 8, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "Medium integer unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1, #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1, #endif }, { "tinyint unsigned auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "tinyint unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1 #else SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1 #endif }, { "smallint auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "smallint auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1 #else SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1 #endif }, { "int unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1 #endif }, { "mediumint", SQL_INTEGER, 7, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "Medium integer", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1 #endif }, { "bit", SQL_BIT, 1, NULL, NULL, NULL, 1, 0, 3, 0, 0, 0, "char(1)", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIT, 0, 0, FIELD_TYPE_TINY, 0 #else SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 0 #endif }, { "numeric", SQL_NUMERIC, 19, NULL, NULL, "precision,scale", 1, 0, 3, 0, 0, 0, "numeric", 0, 19, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_NUMERIC, 0, 0, FIELD_TYPE_DECIMAL, 1, #else SQL_NUMERIC, 0, 0, MYSQL_TYPE_DECIMAL, 1, #endif }, { "integer unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1, #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1, #endif }, { "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL, 1, 0, 3, 1, 0, 0, "Medium integer unsigned", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1 #endif }, { "smallint unsigned auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "smallint unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1 #else SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1 #endif }, { "int auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1 #endif }, { "long varbinary", SQL_LONGVARBINARY, 16777215, "0x", NULL, NULL, 1, 0, 3, 0, 0, 0, "mediumblob", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_LONGVARBINARY, 0, 0, FIELD_TYPE_LONG_BLOB, 0 #else SQL_LONGVARBINARY, 0, 0, MYSQL_TYPE_LONG_BLOB, 0 #endif }, { "double auto_increment", SQL_FLOAT, 15, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 2, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_FLOAT, 0, 0, FIELD_TYPE_DOUBLE, 1 #else SQL_FLOAT, 0, 0, MYSQL_TYPE_DOUBLE, 1 #endif }, { "double auto_increment", SQL_DOUBLE, 15, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_DOUBLE, 0, 0, FIELD_TYPE_DOUBLE, 1 #else SQL_DOUBLE, 0, 0, MYSQL_TYPE_DOUBLE, 1 #endif }, { "integer auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1, #else SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1, #endif }, { "bigint auto_increment", SQL_BIGINT, 19, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "bigint auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1 #else SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1 #endif }, { "bit auto_increment", SQL_BIT, 1, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "char(1) auto_increment", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIT, 0, 0, FIELD_TYPE_TINY, 1 #else SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 1 #endif }, { "mediumint auto_increment", SQL_INTEGER, 7, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "Medium integer auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1 #else SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1 #endif }, { "float auto_increment", SQL_REAL, 7, NULL, NULL, NULL, 0, 0, 0, 0, 0, 1, "float auto_increment", 0, 2, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_FLOAT, 0, 0, FIELD_TYPE_FLOAT, 1 #else SQL_FLOAT, 0, 0, MYSQL_TYPE_FLOAT, 1 #endif }, { "long varchar", SQL_LONGVARCHAR, 16777215, "'", "'", NULL, 1, 0, 3, 0, 0, 0, "mediumtext", 0, 0, 0, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_LONGVARCHAR, 0, 0, FIELD_TYPE_MEDIUM_BLOB, 1 #else SQL_LONGVARCHAR, 0, 0, MYSQL_TYPE_MEDIUM_BLOB, 1 #endif }, { "tinyint auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL, 0, 0, 3, 0, 0, 1, "tinyint auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1 #else SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1 #endif }, { "bigint unsigned auto_increment", SQL_BIGINT, 20, NULL, NULL, NULL, 0, 0, 3, 1, 0, 1, "bigint unsigned auto_increment", 0, 0, 10, #if MYSQL_VERSION_ID < MYSQL_VERSION_5_0 SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1 #else SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1 #endif }, /* END MORE STUFF */ }; /* static const sql_type_info_t* native2sql (int t) */ static const sql_type_info_t *native2sql(int t) { switch (t) { case FIELD_TYPE_VAR_STRING: return &SQL_GET_TYPE_INFO_values[0]; case FIELD_TYPE_DECIMAL: return &SQL_GET_TYPE_INFO_values[1]; #ifdef FIELD_TYPE_NEWDECIMAL case FIELD_TYPE_NEWDECIMAL: return &SQL_GET_TYPE_INFO_values[1]; #endif case FIELD_TYPE_TINY: return &SQL_GET_TYPE_INFO_values[2]; case FIELD_TYPE_SHORT: return &SQL_GET_TYPE_INFO_values[3]; case FIELD_TYPE_LONG: return &SQL_GET_TYPE_INFO_values[4]; case FIELD_TYPE_FLOAT: return &SQL_GET_TYPE_INFO_values[5]; /* 6 */ case FIELD_TYPE_DOUBLE: return &SQL_GET_TYPE_INFO_values[7]; case FIELD_TYPE_TIMESTAMP: return &SQL_GET_TYPE_INFO_values[8]; case FIELD_TYPE_LONGLONG: return &SQL_GET_TYPE_INFO_values[9]; case FIELD_TYPE_INT24: return &SQL_GET_TYPE_INFO_values[10]; case FIELD_TYPE_DATE: return &SQL_GET_TYPE_INFO_values[11]; case FIELD_TYPE_TIME: return &SQL_GET_TYPE_INFO_values[12]; case FIELD_TYPE_DATETIME: return &SQL_GET_TYPE_INFO_values[13]; case FIELD_TYPE_YEAR: return &SQL_GET_TYPE_INFO_values[14]; case FIELD_TYPE_NEWDATE: return &SQL_GET_TYPE_INFO_values[15]; case FIELD_TYPE_ENUM: return &SQL_GET_TYPE_INFO_values[16]; case FIELD_TYPE_SET: return &SQL_GET_TYPE_INFO_values[17]; case FIELD_TYPE_BLOB: return &SQL_GET_TYPE_INFO_values[18]; case FIELD_TYPE_TINY_BLOB: return &SQL_GET_TYPE_INFO_values[19]; case FIELD_TYPE_MEDIUM_BLOB: return &SQL_GET_TYPE_INFO_values[20]; case FIELD_TYPE_LONG_BLOB: return &SQL_GET_TYPE_INFO_values[21]; case FIELD_TYPE_STRING: return &SQL_GET_TYPE_INFO_values[22]; default: return &SQL_GET_TYPE_INFO_values[0]; } } #define SQL_GET_TYPE_INFO_num \ (sizeof(SQL_GET_TYPE_INFO_values)/sizeof(sql_type_info_t)) /*************************************************************************** * * Name: dbd_init * * Purpose: Called when the driver is installed by DBI * * Input: dbistate - pointer to the DBI state variable, used for some * DBI internal things * * Returns: Nothing * **************************************************************************/ void dbd_init(dbistate_t* dbistate) { dTHX; DBISTATE_INIT; } /************************************************************************** * * Name: do_error, do_warn * * Purpose: Called to associate an error code and an error message * to some handle * * Input: h - the handle in error condition * rc - the error code * what - the error message * * Returns: Nothing * **************************************************************************/ void do_error(SV* h, int rc, const char* what, const char* sqlstate) { dTHX; D_imp_xxh(h); STRLEN lna; SV *errstr; SV *errstate; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t--> do_error\n"); errstr= DBIc_ERRSTR(imp_xxh); sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */ sv_setpv(errstr, what); #if MYSQL_VERSION_ID >= SQL_STATE_VERSION if (sqlstate) { errstate= DBIc_STATE(imp_xxh); sv_setpvn(errstate, sqlstate, 5); } #endif /* NO EFFECT DBIh_EVENT2(h, ERROR_event, DBIc_ERR(imp_xxh), errstr); */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s error %d recorded: %s\n", what, rc, SvPV(errstr,lna)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t<-- do_error\n"); } /* void do_warn(SV* h, int rc, char* what) */ void do_warn(SV* h, int rc, char* what) { dTHX; D_imp_xxh(h); STRLEN lna; SV *errstr = DBIc_ERRSTR(imp_xxh); sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */ sv_setpv(errstr, what); /* NO EFFECT DBIh_EVENT2(h, WARN_event, DBIc_ERR(imp_xxh), errstr);*/ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s warning %d recorded: %s\n", what, rc, SvPV(errstr,lna)); warn("%s", what); } #if defined(DBD_MYSQL_EMBEDDED) #define DBD_MYSQL_NAMESPACE "DBD::mysqlEmb::QUIET"; #else #define DBD_MYSQL_NAMESPACE "DBD::mysql::QUIET"; #endif #define doquietwarn(s) \ { \ SV* sv = perl_get_sv(DBD_MYSQL_NAMESPACE, FALSE); \ if (!sv || !SvTRUE(sv)) { \ warn s; \ } \ } /*************************************************************************** * * Name: mysql_dr_connect * * Purpose: Replacement for mysql_connect * * Input: MYSQL* sock - Pointer to a MYSQL structure being * initialized * char* mysql_socket - Name of a UNIX socket being used * or NULL * char* host - Host name being used or NULL for localhost * char* port - Port number being used or NULL for default * char* user - User name being used or NULL * char* password - Password being used or NULL * char* dbname - Database name being used or NULL * char* imp_dbh - Pointer to internal dbh structure * * Returns: The sock argument for success, NULL otherwise; * you have to call do_error in the latter case. * **************************************************************************/ MYSQL *mysql_dr_connect( SV* dbh, MYSQL* sock, char* mysql_socket, char* host, char* port, char* user, char* password, char* dbname, imp_dbh_t *imp_dbh) { int portNr; unsigned int client_flag; MYSQL* result; dTHX; D_imp_xxh(dbh); /* per Monty, already in client.c in API */ /* but still not exist in libmysqld.c */ #if defined(DBD_MYSQL_EMBEDDED) if (host && !*host) host = NULL; #endif portNr= (port && *port) ? atoi(port) : 0; /* already in client.c in API */ /* if (user && !*user) user = NULL; */ /* if (password && !*password) password = NULL; */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: host = |%s|, port = %d," \ " uid = %s, pwd = %s\n", host ? host : "NULL", portNr, user ? user : "NULL", password ? password : "NULL"); { #if defined(DBD_MYSQL_EMBEDDED) if (imp_dbh) { D_imp_drh_from_dbh; SV* sv = DBIc_IMP_DATA(imp_dbh); if (sv && SvROK(sv)) { SV** svp; STRLEN lna; char * options; int server_args_cnt= 0; int server_groups_cnt= 0; int rc= 0; char ** server_args = NULL; char ** server_groups = NULL; HV* hv = (HV*) SvRV(sv); if (SvTYPE(hv) != SVt_PVHV) return NULL; if (!imp_drh->embedded.state) { /* Init embedded server */ if ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) && *svp && SvTRUE(*svp)) { options = SvPV(*svp, lna); imp_drh->embedded.groups=newSVsv(*svp); if ((server_groups_cnt=count_embedded_options(options))) { /* number of server_groups always server_groups+1 */ server_groups=fill_out_embedded_options(DBIc_LOGPIO(imp_xxh), options, 0, (int)lna, ++server_groups_cnt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Groups names passed to embedded server:\n"); print_embedded_options(DBIc_LOGPIO(imp_xxh), server_groups, server_groups_cnt); } } } if ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) && *svp && SvTRUE(*svp)) { options = SvPV(*svp, lna); imp_drh->embedded.args=newSVsv(*svp); if ((server_args_cnt=count_embedded_options(options))) { /* number of server_options always server_options+1 */ server_args=fill_out_embedded_options(DBIc_LOGPIO(imp_xxh), options, 1, (int)lna, ++server_args_cnt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Server options passed to embedded server:\n"); print_embedded_options(DBIc_LOGPIO(imp_xxh), server_args, server_args_cnt); } } } if (mysql_server_init(server_args_cnt, server_args, server_groups)) { do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was not started. \ Could not initialize environment."); return NULL; } imp_drh->embedded.state=1; if (server_args_cnt) free_embedded_options(server_args, server_args_cnt); if (server_groups_cnt) free_embedded_options(server_groups, server_groups_cnt); } else { /* * Check if embedded parameters passed to connect() differ from * first ones */ if ( ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) && *svp && SvTRUE(*svp))) rc =+ abs(sv_cmp(*svp, imp_drh->embedded.groups)); if ( ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) && *svp && SvTRUE(*svp)) ) rc =+ abs(sv_cmp(*svp, imp_drh->embedded.args)); if (rc) { do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was already started. You cannot pass init\ parameters to embedded server once"); return NULL; } } } } #endif #ifdef MYSQL_NO_CLIENT_FOUND_ROWS client_flag = 0; #else client_flag = CLIENT_FOUND_ROWS; #endif mysql_init(sock); if (imp_dbh) { SV* sv = DBIc_IMP_DATA(imp_dbh); DBIc_set(imp_dbh, DBIcf_AutoCommit, TRUE); if (sv && SvROK(sv)) { HV* hv = (HV*) SvRV(sv); SV** svp; STRLEN lna; /* thanks to Peter John Edwards for mysql_init_command */ if ((svp = hv_fetch(hv, "mysql_init_command", 18, FALSE)) && *svp && SvTRUE(*svp)) { char* df = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " init command (%s).\n", df); mysql_options(sock, MYSQL_INIT_COMMAND, df); } if ((svp = hv_fetch(hv, "mysql_compression", 17, FALSE)) && *svp && SvTRUE(*svp)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Enabling" \ " compression.\n"); mysql_options(sock, MYSQL_OPT_COMPRESS, NULL); } if ((svp = hv_fetch(hv, "mysql_connect_timeout", 21, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " connect timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_write_timeout", 19, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " write timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_WRITE_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_read_timeout", 18, FALSE)) && *svp && SvTRUE(*svp)) { int to = SvIV(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Setting" \ " read timeout (%d).\n",to); mysql_options(sock, MYSQL_OPT_READ_TIMEOUT, (const char *)&to); } if ((svp = hv_fetch(hv, "mysql_skip_secure_auth", 22, FALSE)) && *svp && SvTRUE(*svp)) { my_bool secauth = 0; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Skipping" \ " secure auth\n"); mysql_options(sock, MYSQL_SECURE_AUTH, &secauth); } if ((svp = hv_fetch(hv, "mysql_read_default_file", 23, FALSE)) && *svp && SvTRUE(*svp)) { char* df = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Reading" \ " default file %s.\n", df); mysql_options(sock, MYSQL_READ_DEFAULT_FILE, df); } if ((svp = hv_fetch(hv, "mysql_read_default_group", 24, FALSE)) && *svp && SvTRUE(*svp)) { char* gr = SvPV(*svp, lna); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Using" \ " default group %s.\n", gr); mysql_options(sock, MYSQL_READ_DEFAULT_GROUP, gr); } #if (MYSQL_VERSION_ID >= 50606) if ((svp = hv_fetch(hv, "mysql_conn_attrs", 16, FALSE)) && *svp) { HV* attrs = (HV*) SvRV(*svp); HE* entry = NULL; I32 num_entries = hv_iterinit(attrs); while (num_entries && (entry = hv_iternext(attrs))) { I32 retlen = 0; char *attr_name = hv_iterkey(entry, &retlen); SV *sv_attr_val = hv_iterval(attrs, entry); char *attr_val = SvPV(sv_attr_val, lna); mysql_options4(sock, MYSQL_OPT_CONNECT_ATTR_ADD, attr_name, attr_val); } } #endif if ((svp = hv_fetch(hv, "mysql_client_found_rows", 23, FALSE)) && *svp) { if (SvTRUE(*svp)) client_flag |= CLIENT_FOUND_ROWS; else client_flag &= ~CLIENT_FOUND_ROWS; } if ((svp = hv_fetch(hv, "mysql_use_result", 16, FALSE)) && *svp) { imp_dbh->use_mysql_use_result = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_mysql_use_result: %d\n", imp_dbh->use_mysql_use_result); } if ((svp = hv_fetch(hv, "mysql_bind_type_guessing", 24, TRUE)) && *svp) { imp_dbh->bind_type_guessing= SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->bind_type_guessing: %d\n", imp_dbh->bind_type_guessing); } if ((svp = hv_fetch(hv, "mysql_bind_comment_placeholders", 31, FALSE)) && *svp) { imp_dbh->bind_comment_placeholders = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->bind_comment_placeholders: %d\n", imp_dbh->bind_comment_placeholders); } if ((svp = hv_fetch(hv, "mysql_no_autocommit_cmd", 23, FALSE)) && *svp) { imp_dbh->no_autocommit_cmd= SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->no_autocommit_cmd: %d\n", imp_dbh->no_autocommit_cmd); } #if FABRIC_SUPPORT if ((svp = hv_fetch(hv, "mysql_use_fabric", 16, FALSE)) && *svp && SvTRUE(*svp)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_fabric: Enabling use of" \ " MySQL Fabric.\n"); mysql_options(sock, MYSQL_OPT_USE_FABRIC, NULL); } #endif #if defined(CLIENT_MULTI_STATEMENTS) if ((svp = hv_fetch(hv, "mysql_multi_statements", 22, FALSE)) && *svp) { if (SvTRUE(*svp)) client_flag |= CLIENT_MULTI_STATEMENTS; else client_flag &= ~CLIENT_MULTI_STATEMENTS; } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* took out client_flag |= CLIENT_PROTOCOL_41; */ /* because libmysql.c already sets this no matter what */ if ((svp = hv_fetch(hv, "mysql_server_prepare", 20, FALSE)) && *svp) { if (SvTRUE(*svp)) { client_flag |= CLIENT_PROTOCOL_41; imp_dbh->use_server_side_prepare = TRUE; } else { client_flag &= ~CLIENT_PROTOCOL_41; imp_dbh->use_server_side_prepare = FALSE; } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->use_server_side_prepare: %d\n", imp_dbh->use_server_side_prepare); #endif /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if ((svp = hv_fetch(hv, "mysql_enable_utf8mb4", 20, FALSE)) && *svp && SvTRUE(*svp)) { mysql_options(sock, MYSQL_SET_CHARSET_NAME, "utf8mb4"); } else if ((svp = hv_fetch(hv, "mysql_enable_utf8", 17, FALSE)) && *svp) { /* Do not touch imp_dbh->enable_utf8 as we are called earlier * than it is set and mysql_options() must be before: * mysql_real_connect() */ mysql_options(sock, MYSQL_SET_CHARSET_NAME, (SvTRUE(*svp) ? "utf8" : "latin1")); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_options: MYSQL_SET_CHARSET_NAME=%s\n", (SvTRUE(*svp) ? "utf8" : "latin1")); } #endif #if defined(DBD_MYSQL_WITH_SSL) && !defined(DBD_MYSQL_EMBEDDED) && \ (defined(CLIENT_SSL) || (MYSQL_VERSION_ID >= 40000)) if ((svp = hv_fetch(hv, "mysql_ssl", 9, FALSE)) && *svp) { if (SvTRUE(*svp)) { char *client_key = NULL; char *client_cert = NULL; char *ca_file = NULL; char *ca_path = NULL; char *cipher = NULL; STRLEN lna; #if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION && MYSQL_VERSION_ID <= SSL_LAST_VERIFY_VERSION /* New code to utilise MySQLs new feature that verifies that the server's hostname that the client connects to matches that of the certificate */ my_bool ssl_verify_true = 0; if ((svp = hv_fetch(hv, "mysql_ssl_verify_server_cert", 28, FALSE)) && *svp) ssl_verify_true = SvTRUE(*svp); #endif if ((svp = hv_fetch(hv, "mysql_ssl_client_key", 20, FALSE)) && *svp) client_key = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_client_cert", 21, FALSE)) && *svp) client_cert = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_ca_file", 17, FALSE)) && *svp) ca_file = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_ca_path", 17, FALSE)) && *svp) ca_path = SvPV(*svp, lna); if ((svp = hv_fetch(hv, "mysql_ssl_cipher", 16, FALSE)) && *svp) cipher = SvPV(*svp, lna); mysql_ssl_set(sock, client_key, client_cert, ca_file, ca_path, cipher); #if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION && MYSQL_VERSION_ID <= SSL_LAST_VERIFY_VERSION mysql_options(sock, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &ssl_verify_true); #endif client_flag |= CLIENT_SSL; } } #endif #if (MYSQL_VERSION_ID >= 32349) /* * MySQL 3.23.49 disables LOAD DATA LOCAL by default. Use * mysql_local_infile=1 in the DSN to enable it. */ if ((svp = hv_fetch( hv, "mysql_local_infile", 18, FALSE)) && *svp) { unsigned int flag = SvTRUE(*svp); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: Using" \ " local infile %u.\n", flag); mysql_options(sock, MYSQL_OPT_LOCAL_INFILE, (const char *) &flag); } #endif } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: client_flags = %d\n", client_flag); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION client_flag|= CLIENT_MULTI_RESULTS; #endif result = mysql_real_connect(sock, host, user, password, dbname, portNr, mysql_socket, client_flag); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: <-"); if (result) { #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* connection succeeded. */ /* imp_dbh == NULL when mysql_dr_connect() is called from mysql.xs functions (_admin_internal(),_ListDBs()). */ if (!(result->client_flag & CLIENT_PROTOCOL_41) && imp_dbh) imp_dbh->use_server_side_prepare = FALSE; #endif #if MYSQL_ASYNC if(imp_dbh) { imp_dbh->async_query_in_flight = NULL; } #endif /* we turn off Mysql's auto reconnect and handle re-connecting ourselves so that we can keep track of when this happens. */ result->reconnect=0; } else { /* sock was allocated with mysql_init() fixes: https://rt.cpan.org/Ticket/Display.html?id=86153 Safefree(sock); rurban: No, we still need this handle later in mysql_dr_error(). RT #97625. It will be freed as imp_dbh->pmysql in dbd_db_destroy(), which is called by the DESTROY handler. */ } return result; } } /* safe_hv_fetch */ static char *safe_hv_fetch(pTHX_ HV *hv, const char *name, int name_length) { SV** svp; STRLEN len; char *res= NULL; if ((svp= hv_fetch(hv, name, name_length, FALSE))) { res= SvPV(*svp, len); if (!len) res= NULL; } return res; } /* Frontend for mysql_dr_connect */ static int my_login(pTHX_ SV* dbh, imp_dbh_t *imp_dbh) { SV* sv; HV* hv; char* dbname; char* host; char* port; char* user; char* password; char* mysql_socket; int result; D_imp_xxh(dbh); /* TODO- resolve this so that it is set only if DBI is 1.607 */ #define TAKE_IMP_DATA_VERSION 1 #if TAKE_IMP_DATA_VERSION if (DBIc_has(imp_dbh, DBIcf_IMPSET)) { /* eg from take_imp_data() */ if (DBIc_has(imp_dbh, DBIcf_ACTIVE)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "my_login skip connect\n"); /* tell our parent we've adopted an active child */ ++DBIc_ACTIVE_KIDS(DBIc_PARENT_COM(imp_dbh)); return TRUE; } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "my_login IMPSET but not ACTIVE so connect not skipped\n"); } #endif sv = DBIc_IMP_DATA(imp_dbh); if (!sv || !SvROK(sv)) return FALSE; hv = (HV*) SvRV(sv); if (SvTYPE(hv) != SVt_PVHV) return FALSE; host= safe_hv_fetch(aTHX_ hv, "host", 4); port= safe_hv_fetch(aTHX_ hv, "port", 4); user= safe_hv_fetch(aTHX_ hv, "user", 4); password= safe_hv_fetch(aTHX_ hv, "password", 8); dbname= safe_hv_fetch(aTHX_ hv, "database", 8); mysql_socket= safe_hv_fetch(aTHX_ hv, "mysql_socket", 12); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->my_login : dbname = %s, uid = %s, pwd = %s," \ "host = %s, port = %s\n", dbname ? dbname : "NULL", user ? user : "NULL", password ? password : "NULL", host ? host : "NULL", port ? port : "NULL"); if (!imp_dbh->pmysql) { Newz(908, imp_dbh->pmysql, 1, MYSQL); } result = mysql_dr_connect(dbh, imp_dbh->pmysql, mysql_socket, host, port, user, password, dbname, imp_dbh) ? TRUE : FALSE; return result; } /************************************************************************** * * Name: dbd_db_login * * Purpose: Called for connecting to a database and logging in. * * Input: dbh - database handle being initialized * imp_dbh - drivers private database handle data * dbname - the database we want to log into; may be like * "dbname:host" or "dbname:host:port" * user - user name to connect as * password - password to connect with * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_db_login(SV* dbh, imp_dbh_t* imp_dbh, char* dbname, char* user, char* password) { #ifdef dTHR dTHR; #endif dTHX; D_imp_xxh(dbh); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->connect: dsn = %s, uid = %s, pwd = %s\n", dbname ? dbname : "NULL", user ? user : "NULL", password ? password : "NULL"); imp_dbh->stats.auto_reconnects_ok= 0; imp_dbh->stats.auto_reconnects_failed= 0; imp_dbh->bind_type_guessing= FALSE; imp_dbh->bind_comment_placeholders= FALSE; imp_dbh->has_transactions= TRUE; /* Safer we flip this to TRUE perl side if we detect a mod_perl env. */ imp_dbh->auto_reconnect = FALSE; /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION imp_dbh->enable_utf8 = FALSE; /* initialize mysql_enable_utf8 */ imp_dbh->enable_utf8mb4 = FALSE; /* initialize mysql_enable_utf8mb4 */ #endif if (!my_login(aTHX_ dbh, imp_dbh)) { if(imp_dbh->pmysql) { do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql)); Safefree(imp_dbh->pmysql); } return FALSE; } /* * Tell DBI, that dbh->disconnect should be called for this handle */ DBIc_ACTIVE_on(imp_dbh); /* Tell DBI, that dbh->destroy should be called for this handle */ DBIc_on(imp_dbh, DBIcf_IMPSET); return TRUE; } /*************************************************************************** * * Name: dbd_db_commit * dbd_db_rollback * * Purpose: You guess what they should do. * * Input: dbh - database handle being committed or rolled back * imp_dbh - drivers private database handle data * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_db_commit(SV* dbh, imp_dbh_t* imp_dbh) { if (DBIc_has(imp_dbh, DBIcf_AutoCommit)) return FALSE; ASYNC_CHECK_RETURN(dbh, FALSE); if (imp_dbh->has_transactions) { #if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION if (mysql_real_query(imp_dbh->pmysql, "COMMIT", 6)) #else if (mysql_commit(imp_dbh->pmysql)) #endif { do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql)); return FALSE; } } else do_warn(dbh, JW_ERR_NOT_IMPLEMENTED, "Commit ineffective because transactions are not available"); return TRUE; } /* dbd_db_rollback */ int dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh) { /* croak, if not in AutoCommit mode */ if (DBIc_has(imp_dbh, DBIcf_AutoCommit)) return FALSE; ASYNC_CHECK_RETURN(dbh, FALSE); if (imp_dbh->has_transactions) { #if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION if (mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8)) #else if (mysql_rollback(imp_dbh->pmysql)) #endif { do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql)); return FALSE; } } else do_error(dbh, JW_ERR_NOT_IMPLEMENTED, "Rollback ineffective because transactions are not available" ,NULL); return TRUE; } /* *************************************************************************** * * Name: dbd_db_disconnect * * Purpose: Disconnect a database handle from its database * * Input: dbh - database handle being disconnected * imp_dbh - drivers private database handle data * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh) { #ifdef dTHR dTHR; #endif dTHX; D_imp_xxh(dbh); /* We assume that disconnect will always work */ /* since most errors imply already disconnected. */ DBIc_ACTIVE_off(imp_dbh); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->pmysql: %p\n", imp_dbh->pmysql); mysql_close(imp_dbh->pmysql ); /* We don't free imp_dbh since a reference still exists */ /* The DESTROY method is the only one to 'free' memory. */ return TRUE; } /*************************************************************************** * * Name: dbd_discon_all * * Purpose: Disconnect all database handles at shutdown time * * Input: dbh - database handle being disconnected * imp_dbh - drivers private database handle data * * Returns: TRUE for success, FALSE otherwise; do_error has already * been called in the latter case * **************************************************************************/ int dbd_discon_all (SV *drh, imp_drh_t *imp_drh) { #if defined(dTHR) dTHR; #endif dTHX; D_imp_xxh(drh); #if defined(DBD_MYSQL_EMBEDDED) if (imp_drh->embedded.state) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Stop embedded server\n"); mysql_server_end(); if (imp_drh->embedded.groups) { (void) SvREFCNT_dec(imp_drh->embedded.groups); imp_drh->embedded.groups = NULL; } if (imp_drh->embedded.args) { (void) SvREFCNT_dec(imp_drh->embedded.args); imp_drh->embedded.args = NULL; } } #else mysql_server_end(); #endif /* The disconnect_all concept is flawed and needs more work */ if (!PL_dirty && !SvTRUE(perl_get_sv("DBI::PERL_ENDING",0))) { sv_setiv(DBIc_ERR(imp_drh), (IV)1); sv_setpv(DBIc_ERRSTR(imp_drh), (char*)"disconnect_all not implemented"); /* NO EFFECT DBIh_EVENT2(drh, ERROR_event, DBIc_ERR(imp_drh), DBIc_ERRSTR(imp_drh)); */ return FALSE; } PL_perl_destruct_level = 0; return FALSE; } /**************************************************************************** * * Name: dbd_db_destroy * * Purpose: Our part of the dbh destructor * * Input: dbh - database handle being destroyed * imp_dbh - drivers private database handle data * * Returns: Nothing * **************************************************************************/ void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh) { /* * Being on the safe side never hurts ... */ if (DBIc_ACTIVE(imp_dbh)) { if (imp_dbh->has_transactions) { if (!DBIc_has(imp_dbh, DBIcf_AutoCommit)) #if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION if ( mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8)) #else if (mysql_rollback(imp_dbh->pmysql)) #endif do_error(dbh, TX_ERR_ROLLBACK,"ROLLBACK failed" ,NULL); } dbd_db_disconnect(dbh, imp_dbh); } Safefree(imp_dbh->pmysql); /* Tell DBI, that dbh->destroy must no longer be called */ DBIc_off(imp_dbh, DBIcf_IMPSET); } /* *************************************************************************** * * Name: dbd_db_STORE_attrib * * Purpose: Function for storing dbh attributes; we currently support * just nothing. :-) * * Input: dbh - database handle being modified * imp_dbh - drivers private database handle data * keysv - the attribute name * valuesv - the attribute value * * Returns: TRUE for success, FALSE otherwise * **************************************************************************/ int dbd_db_STORE_attrib( SV* dbh, imp_dbh_t* imp_dbh, SV* keysv, SV* valuesv ) { dTHX; STRLEN kl; char *key = SvPV(keysv, kl); SV *cachesv = Nullsv; int cacheit = FALSE; const bool bool_value = SvTRUE(valuesv); if (kl==10 && strEQ(key, "AutoCommit")) { if (imp_dbh->has_transactions) { bool oldval = DBIc_has(imp_dbh,DBIcf_AutoCommit) ? 1 : 0; if (bool_value == oldval) return TRUE; /* if setting AutoCommit on ... */ if (!imp_dbh->no_autocommit_cmd) { if ( #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION mysql_autocommit(imp_dbh->pmysql, bool_value) #else mysql_real_query(imp_dbh->pmysql, bool_value ? "SET AUTOCOMMIT=1" : "SET AUTOCOMMIT=0", 16) #endif ) { do_error(dbh, TX_ERR_AUTOCOMMIT, bool_value ? "Turning on AutoCommit failed" : "Turning off AutoCommit failed" ,NULL); return TRUE; /* TRUE means we handled it - important to avoid spurious errors */ } } DBIc_set(imp_dbh, DBIcf_AutoCommit, bool_value); } else { /* * We do support neither transactions nor "AutoCommit". * But we stub it. :-) */ if (!bool_value) { do_error(dbh, JW_ERR_NOT_IMPLEMENTED, "Transactions not supported by database" ,NULL); croak("Transactions not supported by database"); } } } else if (kl == 16 && strEQ(key,"mysql_use_result")) imp_dbh->use_mysql_use_result = bool_value; else if (kl == 20 && strEQ(key,"mysql_auto_reconnect")) imp_dbh->auto_reconnect = bool_value; else if (kl == 20 && strEQ(key, "mysql_server_prepare")) imp_dbh->use_server_side_prepare = bool_value; else if (kl == 23 && strEQ(key,"mysql_no_autocommit_cmd")) imp_dbh->no_autocommit_cmd = bool_value; else if (kl == 24 && strEQ(key,"mysql_bind_type_guessing")) imp_dbh->bind_type_guessing = bool_value; else if (kl == 31 && strEQ(key,"mysql_bind_comment_placeholders")) imp_dbh->bind_type_guessing = bool_value; #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION else if (kl == 17 && strEQ(key, "mysql_enable_utf8")) imp_dbh->enable_utf8 = bool_value; else if (kl == 20 && strEQ(key, "mysql_enable_utf8mb4")) imp_dbh->enable_utf8mb4 = bool_value; #endif #if FABRIC_SUPPORT else if (kl == 22 && strEQ(key, "mysql_fabric_opt_group")) mysql_options(imp_dbh->pmysql, FABRIC_OPT_GROUP, (void *)SvPVbyte_nolen(valuesv)); else if (kl == 29 && strEQ(key, "mysql_fabric_opt_default_mode")) { if (SvOK(valuesv)) { STRLEN len; const char *str = SvPVbyte(valuesv, len); if ( len == 0 || ( len == 2 && (strnEQ(str, "ro", 3) || strnEQ(str, "rw", 3)) ) ) mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, len == 0 ? NULL : str); else croak("Valid settings for FABRIC_OPT_DEFAULT_MODE are 'ro', 'rw', or undef/empty string"); } else { mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, NULL); } } else if (kl == 21 && strEQ(key, "mysql_fabric_opt_mode")) { STRLEN len; const char *str = SvPVbyte(valuesv, len); if (len != 2 || (strnNE(str, "ro", 3) && strnNE(str, "rw", 3))) croak("Valid settings for FABRIC_OPT_MODE are 'ro' or 'rw'"); mysql_options(imp_dbh->pmysql, FABRIC_OPT_MODE, str); } else if (kl == 34 && strEQ(key, "mysql_fabric_opt_group_credentials")) { croak("'fabric_opt_group_credentials' is not supported"); } #endif else return FALSE; /* Unknown key */ if (cacheit) /* cache value for later DBI 'quick' fetch? */ (void)hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0); return TRUE; } /*************************************************************************** * * Name: dbd_db_FETCH_attrib * * Purpose: Function for fetching dbh attributes * * Input: dbh - database handle being queried * imp_dbh - drivers private database handle data * keysv - the attribute name * * Returns: An SV*, if successful; NULL otherwise * * Notes: Do not forget to call sv_2mortal in the former case! * **************************************************************************/ static SV* my_ulonglong2str(pTHX_ my_ulonglong val) { char buf[64]; char *ptr = buf + sizeof(buf) - 1; if (val == 0) return newSVpvn("0", 1); *ptr = '\0'; while (val > 0) { *(--ptr) = ('0' + (val % 10)); val = val / 10; } return newSVpvn(ptr, (buf+ sizeof(buf) - 1) - ptr); } SV* dbd_db_FETCH_attrib(SV *dbh, imp_dbh_t *imp_dbh, SV *keysv) { dTHX; STRLEN kl; char *key = SvPV(keysv, kl); SV* result = NULL; dbh= dbh; switch (*key) { case 'A': if (strEQ(key, "AutoCommit")) { if (imp_dbh->has_transactions) return sv_2mortal(boolSV(DBIc_has(imp_dbh,DBIcf_AutoCommit))); /* Default */ return &PL_sv_yes; } break; } if (strncmp(key, "mysql_", 6) == 0) { key = key+6; kl = kl-6; } /* MONTY: Check if kl should not be used or used everywhere */ switch(*key) { case 'a': if (kl == strlen("auto_reconnect") && strEQ(key, "auto_reconnect")) result= sv_2mortal(newSViv(imp_dbh->auto_reconnect)); break; case 'b': if (kl == strlen("bind_type_guessing") && strEQ(key, "bind_type_guessing")) { result = sv_2mortal(newSViv(imp_dbh->bind_type_guessing)); } else if (kl == strlen("bind_comment_placeholders") && strEQ(key, "bind_comment_placeholders")) { result = sv_2mortal(newSViv(imp_dbh->bind_comment_placeholders)); } break; case 'c': if (kl == 10 && strEQ(key, "clientinfo")) { const char* clientinfo = mysql_get_client_info(); result= clientinfo ? sv_2mortal(newSVpvn(clientinfo, strlen(clientinfo))) : &PL_sv_undef; } else if (kl == 13 && strEQ(key, "clientversion")) { result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_client_version())); } break; case 'e': if (strEQ(key, "errno")) result= sv_2mortal(newSViv((IV)mysql_errno(imp_dbh->pmysql))); else if ( strEQ(key, "error") || strEQ(key, "errmsg")) { /* Note that errmsg is obsolete, as of 2.09! */ const char* msg = mysql_error(imp_dbh->pmysql); result= sv_2mortal(newSVpvn(msg, strlen(msg))); } /* HELMUT */ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION else if (kl == strlen("enable_utf8mb4") && strEQ(key, "enable_utf8mb4")) result = sv_2mortal(newSViv(imp_dbh->enable_utf8mb4)); else if (kl == strlen("enable_utf8") && strEQ(key, "enable_utf8")) result = sv_2mortal(newSViv(imp_dbh->enable_utf8)); #endif break; case 'd': if (strEQ(key, "dbd_stats")) { HV* hv = newHV(); (void)hv_store( hv, "auto_reconnects_ok", strlen("auto_reconnects_ok"), newSViv(imp_dbh->stats.auto_reconnects_ok), 0 ); (void)hv_store( hv, "auto_reconnects_failed", strlen("auto_reconnects_failed"), newSViv(imp_dbh->stats.auto_reconnects_failed), 0 ); result= sv_2mortal((newRV_noinc((SV*)hv))); } case 'h': if (strEQ(key, "hostinfo")) { const char* hostinfo = mysql_get_host_info(imp_dbh->pmysql); result= hostinfo ? sv_2mortal(newSVpvn(hostinfo, strlen(hostinfo))) : &PL_sv_undef; } break; case 'i': if (strEQ(key, "info")) { const char* info = mysql_info(imp_dbh->pmysql); result= info ? sv_2mortal(newSVpvn(info, strlen(info))) : &PL_sv_undef; } else if (kl == 8 && strEQ(key, "insertid")) /* We cannot return an IV, because the insertid is a long. */ result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql))); break; case 'n': if (kl == strlen("no_autocommit_cmd") && strEQ(key, "no_autocommit_cmd")) result = sv_2mortal(newSViv(imp_dbh->no_autocommit_cmd)); break; case 'p': if (kl == 9 && strEQ(key, "protoinfo")) result= sv_2mortal(newSViv(mysql_get_proto_info(imp_dbh->pmysql))); break; case 's': if (kl == 10 && strEQ(key, "serverinfo")) { const char* serverinfo = mysql_get_server_info(imp_dbh->pmysql); result= serverinfo ? sv_2mortal(newSVpvn(serverinfo, strlen(serverinfo))) : &PL_sv_undef; } else if (kl == 13 && strEQ(key, "serverversion")) result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_server_version(imp_dbh->pmysql))); else if (strEQ(key, "sock")) result= sv_2mortal(newSViv(PTR2IV(imp_dbh->pmysql))); else if (strEQ(key, "sockfd")) result= sv_2mortal(newSViv((IV) imp_dbh->pmysql->net.fd)); else if (strEQ(key, "stat")) { const char* stats = mysql_stat(imp_dbh->pmysql); result= stats ? sv_2mortal(newSVpvn(stats, strlen(stats))) : &PL_sv_undef; } else if (strEQ(key, "stats")) { /* Obsolete, as of 2.09 */ const char* stats = mysql_stat(imp_dbh->pmysql); result= stats ? sv_2mortal(newSVpvn(stats, strlen(stats))) : &PL_sv_undef; } else if (kl == 14 && strEQ(key,"server_prepare")) result= sv_2mortal(newSViv((IV) imp_dbh->use_server_side_prepare)); break; case 't': if (kl == 9 && strEQ(key, "thread_id")) result= sv_2mortal(newSViv(mysql_thread_id(imp_dbh->pmysql))); break; case 'w': if (kl == 13 && strEQ(key, "warning_count")) result= sv_2mortal(newSViv(mysql_warning_count(imp_dbh->pmysql))); break; case 'u': if (strEQ(key, "use_result")) { result= sv_2mortal(newSViv((IV) imp_dbh->use_mysql_use_result)); } break; } if (result== NULL) return Nullsv; return result; } /* ************************************************************************** * * Name: dbd_st_prepare * * Purpose: Called for preparing an SQL statement; our part of the * statement handle constructor * * Input: sth - statement handle being initialized * imp_sth - drivers private statement handle data * statement - pointer to string with SQL statement * attribs - statement attributes, currently not in use * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_prepare( SV *sth, imp_sth_t *imp_sth, char *statement, SV *attribs) { int i; SV **svp; dTHX; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION char *str_ptr, *str_last_ptr; #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION int limit_flag=0; #endif #endif int prepare_retval; MYSQL_BIND *bind, *bind_end; imp_sth_phb_t *fbind; #endif D_imp_xxh(sth); D_imp_dbh_from_sth; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n", MYSQL_VERSION_ID, statement); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Set default value of 'mysql_server_prepare' attribute for sth from dbh */ imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare; if (attribs) { svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_server_prepare", 20); imp_sth->use_server_side_prepare = (svp) ? SvTRUE(*svp) : imp_dbh->use_server_side_prepare; svp = DBD_ATTRIB_GET_SVP(attribs, "async", 5); if(svp && SvTRUE(*svp)) { #if MYSQL_ASYNC imp_sth->is_async = TRUE; imp_sth->use_server_side_prepare = FALSE; #else do_error(sth, 2000, "Async support was not built into this version of DBD::mysql", "HY000"); return 0; #endif } } imp_sth->fetch_done= 0; #endif imp_sth->done_desc= 0; imp_sth->result= NULL; imp_sth->currow= 0; /* Set default value of 'mysql_use_result' attribute for sth from dbh */ svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_use_result", 16); imp_sth->use_mysql_use_result= svp ? SvTRUE(*svp) : imp_dbh->use_mysql_use_result; for (i= 0; i < AV_ATTRIB_LAST; i++) imp_sth->av_attr[i]= Nullav; /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets(sth, imp_sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tuse_server_side_prepare set, check restrictions\n"); /* This code is here because placeholder support is not implemented for statements with :- 1. LIMIT < 5.0.7 2. CALL < 5.5.3 (Added support for out & inout parameters) In these cases we have to disable server side prepared statements NOTE: These checks could cause a false positive on statements which include columns / table names that match "call " or " limit " */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION "\t\tneed to test for LIMIT & CALL\n"); #else "\t\tneed to test for restrictions\n"); #endif str_last_ptr = statement + strlen(statement); for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++) { #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION /* Place holders not supported in LIMIT's */ if (limit_flag) { if (*str_ptr == '?') { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tLIMIT and ? found, set to use_server_side_prepare=0\n"); /* ... then we do not want to try server side prepare (use emulation) */ imp_sth->use_server_side_prepare= 0; break; } } else if (str_ptr < str_last_ptr - 6 && isspace(*(str_ptr + 0)) && tolower(*(str_ptr + 1)) == 'l' && tolower(*(str_ptr + 2)) == 'i' && tolower(*(str_ptr + 3)) == 'm' && tolower(*(str_ptr + 4)) == 'i' && tolower(*(str_ptr + 5)) == 't' && isspace(*(str_ptr + 6))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "LIMIT set limit flag to 1\n"); limit_flag= 1; } #endif /* Place holders not supported in CALL's */ if (str_ptr < str_last_ptr - 4 && tolower(*(str_ptr + 0)) == 'c' && tolower(*(str_ptr + 1)) == 'a' && tolower(*(str_ptr + 2)) == 'l' && tolower(*(str_ptr + 3)) == 'l' && isspace(*(str_ptr + 4))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Disable PS mode for CALL()\n"); imp_sth->use_server_side_prepare= 0; break; } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tuse_server_side_prepare set\n"); /* do we really need this? If we do, we should return, not just continue */ if (imp_sth->stmt) fprintf(stderr, "ERROR: Trying to prepare new stmt while we have \ already not closed one \n"); imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql); if (! imp_sth->stmt) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tERROR: Unable to return MYSQL_STMT structure \ from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n", mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql)); } prepare_retval= mysql_stmt_prepare(imp_sth->stmt, statement, strlen(statement)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_stmt_prepare returned %d\n", prepare_retval); if (prepare_retval) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_stmt_prepare %d %s\n", mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt)); /* For commands that are not supported by server side prepared statement mechanism lets try to pass them through regular API */ if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tSETTING imp_sth->use_server_side_prepare to 0\n"); imp_sth->use_server_side_prepare= 0; } else { do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_sqlstate(imp_dbh->pmysql)); mysql_stmt_close(imp_sth->stmt); imp_sth->stmt= NULL; return FALSE; } } else { DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt); /* mysql_stmt_param_count */ if (DBIc_NUM_PARAMS(imp_sth) > 0) { /* Allocate memory for bind variables */ imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->has_been_bound= 0; /* Initialize ph variables with NULL values */ for (i= 0, bind= imp_sth->bind, fbind= imp_sth->fbind, bind_end= bind+DBIc_NUM_PARAMS(imp_sth); bind < bind_end ; bind++, fbind++, i++ ) { bind->buffer_type= MYSQL_TYPE_STRING; bind->buffer= NULL; bind->length= &(fbind->length); bind->is_null= (char*) &(fbind->is_null); fbind->is_null= 1; fbind->length= 0; } } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Count the number of parameters (driver, vs server-side) */ if (imp_sth->use_server_side_prepare == 0) DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #else DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #endif /* Allocate memory for parameters */ imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth)); DBIc_IMPSET_on(imp_sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_prepare\n"); return 1; } /*************************************************************************** * Name: dbd_st_free_result_sets * * Purpose: Clean-up single or multiple result sets (if any) * * Inputs: sth - Statement handle * imp_sth - driver's private statement handle * * Returns: 1 ok * 0 error *************************************************************************/ int mysql_st_free_result_sets (SV * sth, imp_sth_t * imp_sth) { dTHX; D_imp_dbh_from_sth; D_imp_xxh(sth); int next_result_rc= -1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t>- dbd_st_free_result_sets\n"); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION do { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets RC %d\n", next_result_rc); if (next_result_rc == 0) { if (!(imp_sth->result = mysql_use_result(imp_dbh->pmysql))) { /* Check for possible error */ if (mysql_field_count(imp_dbh->pmysql)) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets ERROR: %s\n", mysql_error(imp_dbh->pmysql)); do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); return 0; } } } if (imp_sth->result) { mysql_free_result(imp_sth->result); imp_sth->result=NULL; } } while ((next_result_rc=mysql_next_result(imp_dbh->pmysql))==0); if (next_result_rc > 0) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets: Error while processing multi-result set: %s\n", mysql_error(imp_dbh->pmysql)); do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); } #else if (imp_sth->result) { mysql_free_result(imp_sth->result); imp_sth->result=NULL; } #endif if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets\n"); return 1; } #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION /*************************************************************************** * Name: dbd_st_more_results * * Purpose: Move onto the next result set (if any) * * Inputs: sth - Statement handle * imp_sth - driver's private statement handle * * Returns: 1 if there are more results sets * 0 if there are not * -1 for errors. *************************************************************************/ int dbd_st_more_results(SV* sth, imp_sth_t* imp_sth) { dTHX; D_imp_dbh_from_sth; D_imp_xxh(sth); int use_mysql_use_result=imp_sth->use_mysql_use_result; int next_result_return_code, i; MYSQL* svsock= imp_dbh->pmysql; if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV) croak("Expected hash array"); if (!mysql_more_results(svsock)) { /* No more pending result set(s)*/ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n <- dbs_st_more_results no more results\n"); return 0; } if (imp_sth->use_server_side_prepare) { do_warn(sth, JW_ERR_NOT_IMPLEMENTED, "Processing of multiple result set is not possible with server side prepare"); return 0; } /* * Free cached array attributes */ for (i= 0; i < AV_ATTRIB_LAST; i++) { if (imp_sth->av_attr[i]) SvREFCNT_dec(imp_sth->av_attr[i]); imp_sth->av_attr[i]= Nullav; } /* Release previous MySQL result*/ if (imp_sth->result) mysql_free_result(imp_sth->result); if (DBIc_ACTIVE(imp_sth)) DBIc_ACTIVE_off(imp_sth); next_result_return_code= mysql_next_result(svsock); imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql); /* mysql_next_result returns 0 if there are more results -1 if there are no more results >0 if there was an error */ if (next_result_return_code > 0) { do_error(sth, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); return 0; } else if(next_result_return_code == -1) { return 0; } else { /* Store the result from the Query */ imp_sth->result = use_mysql_use_result ? mysql_use_result(svsock) : mysql_store_result(svsock); if (mysql_errno(svsock)) { do_error(sth, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); return 0; } imp_sth->row_num= mysql_affected_rows(imp_dbh->pmysql); if (imp_sth->result == NULL) { /* No "real" rowset*/ DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */ DBIS->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0, sv_2mortal(newSViv(0))); return 1; } else { /* We have a new rowset */ imp_sth->currow=0; /* delete cached handle attributes */ /* XXX should be driven by a list to ease maintenance */ (void)hv_delete((HV*)SvRV(sth), "NAME", 4, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "NULLABLE", 8, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "NUM_OF_FIELDS", 13, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "PRECISION", 9, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "SCALE", 5, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "TYPE", 4, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_insertid", 14, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_is_auto_increment", 23, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_is_blob", 13, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_is_key", 12, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_is_num", 12, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_is_pri_key", 16, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_length", 12, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_max_length", 16, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_table", 11, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_type", 10, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_type_name", 15, G_DISCARD); (void)hv_delete((HV*)SvRV(sth), "mysql_warning_count", 20, G_DISCARD); /* Adjust NUM_OF_FIELDS - which also adjusts the row buffer size */ DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */ DBIc_DBISTATE(imp_sth)->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0, sv_2mortal(newSViv(mysql_num_fields(imp_sth->result))) ); DBIc_ACTIVE_on(imp_sth); imp_sth->done_desc = 0; } imp_dbh->pmysql->net.last_errno= 0; return 1; } } #endif /************************************************************************** * * Name: mysql_st_internal_execute * * Purpose: Internal version for executing a statement, called both from * within the "do" and the "execute" method. * * Inputs: h - object handle, for storing error messages * statement - query being executed * attribs - statement attributes, currently ignored * num_params - number of parameters being bound * params - parameter array * result - where to store results, if any * svsock - socket connected to the database * **************************************************************************/ my_ulonglong mysql_st_internal_execute( SV *h, /* could be sth or dbh */ SV *statement, SV *attribs, int num_params, imp_sth_ph_t *params, MYSQL_RES **result, MYSQL *svsock, int use_mysql_use_result ) { dTHX; bool bind_type_guessing= FALSE; bool bind_comment_placeholders= TRUE; STRLEN slen; char *sbuf = SvPV(statement, slen); char *table; char *salloc; int htype; #if MYSQL_ASYNC bool async = FALSE; #endif my_ulonglong rows= 0; /* thank you DBI.c for this info! */ D_imp_xxh(h); attribs= attribs; htype= DBIc_TYPE(imp_xxh); /* It is important to import imp_dbh properly according to the htype that it is! Also, one might ask why bind_type_guessing is assigned in each block. Well, it's because D_imp_ macros called in these blocks make it so imp_dbh is not "visible" or defined outside of the if/else (when compiled, it fails for imp_dbh not being defined). */ /* h is a dbh */ if (htype == DBIt_DB) { D_imp_dbh(h); /* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */ if (imp_dbh && imp_dbh->bind_type_guessing) { bind_type_guessing= imp_dbh->bind_type_guessing; bind_comment_placeholders= bind_comment_placeholders; } #if MYSQL_ASYNC async = (bool) (imp_dbh->async_query_in_flight != NULL); #endif } /* h is a sth */ else { D_imp_sth(h); D_imp_dbh_from_sth; /* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */ if (imp_dbh) { bind_type_guessing= imp_dbh->bind_type_guessing; bind_comment_placeholders= imp_dbh->bind_comment_placeholders; } #if MYSQL_ASYNC async = imp_sth->is_async; if(async) { imp_dbh->async_query_in_flight = imp_sth; } else { imp_dbh->async_query_in_flight = NULL; } #endif } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_st_internal_execute MYSQL_VERSION_ID %d\n", MYSQL_VERSION_ID ); salloc= parse_params(imp_xxh, aTHX_ svsock, sbuf, &slen, params, num_params, bind_type_guessing, bind_comment_placeholders); if (salloc) { sbuf= salloc; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Binding parameters: %s\n", sbuf); } if (slen >= 11 && (!strncmp(sbuf, "listfields ", 11) || !strncmp(sbuf, "LISTFIELDS ", 11))) { /* remove pre-space */ slen-= 10; sbuf+= 10; while (slen && isspace(*sbuf)) { --slen; ++sbuf; } if (!slen) { do_error(h, JW_ERR_QUERY, "Missing table name" ,NULL); return -2; } if (!(table= malloc(slen+1))) { do_error(h, JW_ERR_MEM, "Out of memory" ,NULL); return -2; } strncpy(table, sbuf, slen); sbuf= table; while (slen && !isspace(*sbuf)) { --slen; ++sbuf; } *sbuf++= '\0'; *result= mysql_list_fields(svsock, table, NULL); free(table); if (!(*result)) { do_error(h, mysql_errno(svsock), mysql_error(svsock) ,mysql_sqlstate(svsock)); return -2; } return 0; } #if MYSQL_ASYNC if(async) { if((mysql_send_query(svsock, sbuf, slen)) && (!mysql_db_reconnect(h) || (mysql_send_query(svsock, sbuf, slen)))) { rows = -2; } else { rows = 0; } } else { #endif if ((mysql_real_query(svsock, sbuf, slen)) && (!mysql_db_reconnect(h) || (mysql_real_query(svsock, sbuf, slen)))) { rows = -2; } else { /** Store the result from the Query */ *result= use_mysql_use_result ? mysql_use_result(svsock) : mysql_store_result(svsock); if (mysql_errno(svsock)) rows = -2; else if (*result) rows = mysql_num_rows(*result); else { rows = mysql_affected_rows(svsock); /* mysql_affected_rows(): -1 indicates that the query returned an error */ if (rows == (my_ulonglong)-1) rows = -2; } } #if MYSQL_ASYNC } #endif if (salloc) Safefree(salloc); if(rows == (my_ulonglong)-2) { do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "IGNORING ERROR errno %d\n", mysql_errno(svsock)); } return(rows); } /************************************************************************** * * Name: mysql_st_internal_execute41 * * Purpose: Internal version for executing a prepared statement, called both * from within the "do" and the "execute" method. * MYSQL 4.1 API * * * Inputs: h - object handle, for storing error messages * statement - query being executed * attribs - statement attributes, currently ignored * num_params - number of parameters being bound * params - parameter array * result - where to store results, if any * svsock - socket connected to the database * **************************************************************************/ #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION my_ulonglong mysql_st_internal_execute41( SV *sth, int num_params, MYSQL_RES **result, MYSQL_STMT *stmt, MYSQL_BIND *bind, int *has_been_bound ) { int i; enum enum_field_types enum_type; dTHX; int execute_retval; my_ulonglong rows=0; D_imp_xxh(sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> mysql_st_internal_execute41\n"); /* free result if exists */ if (*result) { mysql_free_result(*result); *result= 0; } /* If were performed any changes with ph variables we have to rebind them */ if (num_params > 0 && !(*has_been_bound)) { if (mysql_stmt_bind_param(stmt,bind)) goto error; *has_been_bound= 1; } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_st_internal_execute41 calling mysql_execute with %d num_params\n", num_params); execute_retval= mysql_stmt_execute(stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_stmt_execute returned %d\n", execute_retval); if (execute_retval) goto error; /* This statement does not return a result set (INSERT, UPDATE...) */ if (!(*result= mysql_stmt_result_metadata(stmt))) { if (mysql_stmt_errno(stmt)) goto error; rows= mysql_stmt_affected_rows(stmt); /* mysql_stmt_affected_rows(): -1 indicates that the query returned an error */ if (rows == (my_ulonglong)-1) goto error; } /* This statement returns a result set (SELECT...) */ else { for (i = mysql_stmt_field_count(stmt) - 1; i >=0; --i) { enum_type = mysql_to_perl_type(stmt->fields[i].type); if (enum_type != MYSQL_TYPE_DOUBLE && enum_type != MYSQL_TYPE_LONG && enum_type != MYSQL_TYPE_BIT) { /* mysql_stmt_store_result to update MYSQL_FIELD->max_length */ my_bool on = 1; mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &on); break; } } /* Get the total rows affected and return */ if (mysql_stmt_store_result(stmt)) goto error; else rows= mysql_stmt_num_rows(stmt); } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- mysql_internal_execute_41 returning %llu rows\n", rows); return(rows); error: if (*result) { mysql_free_result(*result); *result= 0; } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " errno %d err message %s\n", mysql_stmt_errno(stmt), mysql_stmt_error(stmt)); do_error(sth, mysql_stmt_errno(stmt), mysql_stmt_error(stmt), mysql_stmt_sqlstate(stmt)); mysql_stmt_reset(stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- mysql_st_internal_execute41\n"); return -2; } #endif /*************************************************************************** * * Name: dbd_st_execute * * Purpose: Called for preparing an SQL statement; our part of the * statement handle constructor * * Input: sth - statement handle being initialized * imp_sth - drivers private statement handle data * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_execute(SV* sth, imp_sth_t* imp_sth) { dTHX; char actual_row_num[64]; int i; SV **statement; D_imp_dbh_from_sth; D_imp_xxh(sth); #if defined (dTHR) dTHR; #endif ASYNC_CHECK_RETURN(sth, -2); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " -> dbd_st_execute for %p\n", sth); if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV) croak("Expected hash array"); /* Free cached array attributes */ for (i= 0; i < AV_ATTRIB_LAST; i++) { if (imp_sth->av_attr[i]) SvREFCNT_dec(imp_sth->av_attr[i]); imp_sth->av_attr[i]= Nullav; } statement= hv_fetch((HV*) SvRV(sth), "Statement", 9, FALSE); /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets (sth, imp_sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare && ! imp_sth->use_mysql_use_result) { imp_sth->row_num= mysql_st_internal_execute41( sth, DBIc_NUM_PARAMS(imp_sth), &imp_sth->result, imp_sth->stmt, imp_sth->bind, &imp_sth->has_been_bound ); } else { #endif imp_sth->row_num= mysql_st_internal_execute( sth, *statement, NULL, DBIc_NUM_PARAMS(imp_sth), imp_sth->params, &imp_sth->result, imp_dbh->pmysql, imp_sth->use_mysql_use_result ); #if MYSQL_ASYNC if(imp_dbh->async_query_in_flight) { DBIc_ACTIVE_on(imp_sth); return 0; } #endif } if (imp_sth->row_num+1 != (my_ulonglong)-1) { if (!imp_sth->result) { imp_sth->insertid= mysql_insert_id(imp_dbh->pmysql); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if (mysql_more_results(imp_dbh->pmysql)) DBIc_ACTIVE_on(imp_sth); #endif } else { /** Store the result in the current statement handle */ DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result); DBIc_ACTIVE_on(imp_sth); if (!imp_sth->use_server_side_prepare) imp_sth->done_desc= 0; imp_sth->fetch_done= 0; } } imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { /* PerlIO_printf doesn't always handle imp_sth->row_num %llu consistently!! */ sprintf(actual_row_num, "%llu", imp_sth->row_num); PerlIO_printf(DBIc_LOGPIO(imp_xxh), " <- dbd_st_execute returning imp_sth->row_num %s\n", actual_row_num); } return (int)imp_sth->row_num; } /************************************************************************** * * Name: dbd_describe * * Purpose: Called from within the fetch method to describe the result * * Input: sth - statement handle being initialized * imp_sth - our part of the statement handle, there's no * need for supplying both; Tim just doesn't remove it * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_describe(SV* sth, imp_sth_t* imp_sth) { dTHX; D_imp_xxh(sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t--> dbd_describe\n"); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { int i; int col_type; int num_fields= DBIc_NUM_FIELDS(imp_sth); imp_sth_fbh_t *fbh; MYSQL_BIND *buffer; MYSQL_FIELD *fields; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_describe() num_fields %d\n", num_fields); if (imp_sth->done_desc) return TRUE; if (!num_fields || !imp_sth->result) { /* no metadata */ do_error(sth, JW_ERR_SEQUENCE, "no metadata information while trying describe result set", NULL); return 0; } /* allocate fields buffers */ if ( !(imp_sth->fbh= alloc_fbuffer(num_fields)) || !(imp_sth->buffer= alloc_bind(num_fields)) ) { /* Out of memory */ do_error(sth, JW_ERR_SEQUENCE, "Out of memory in dbd_sescribe()",NULL); return 0; } fields= mysql_fetch_fields(imp_sth->result); for ( fbh= imp_sth->fbh, buffer= (MYSQL_BIND*)imp_sth->buffer, i= 0; i < num_fields; i++, fbh++, buffer++ ) { /* get the column type */ col_type = fields ? fields[i].type : MYSQL_TYPE_STRING; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\ti %d col_type %d fbh->length %lu\n", i, col_type, fbh->length); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tfields[i].length %lu fields[i].max_length %lu fields[i].type %d fields[i].charsetnr %d\n", fields[i].length, fields[i].max_length, fields[i].type, fields[i].charsetnr); } fbh->charsetnr = fields[i].charsetnr; #if MYSQL_VERSION_ID < FIELD_CHARSETNR_VERSION fbh->flags = fields[i].flags; #endif buffer->buffer_type= mysql_to_perl_type(col_type); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n", col_type); buffer->length= &(fbh->length); buffer->is_null= (my_bool*) &(fbh->is_null); buffer->error= (my_bool*) &(fbh->error); switch (buffer->buffer_type) { case MYSQL_TYPE_DOUBLE: buffer->buffer_length= sizeof(fbh->ddata); buffer->buffer= (char*) &fbh->ddata; break; case MYSQL_TYPE_LONG: buffer->buffer_length= sizeof(fbh->ldata); buffer->buffer= (char*) &fbh->ldata; buffer->is_unsigned= (fields[i].flags & UNSIGNED_FLAG) ? 1 : 0; break; case MYSQL_TYPE_BIT: buffer->buffer_length= 8; Newz(908, fbh->data, buffer->buffer_length, char); buffer->buffer= (char *) fbh->data; break; default: buffer->buffer_length= fields[i].max_length ? fields[i].max_length : 1; Newz(908, fbh->data, buffer->buffer_length, char); buffer->buffer= (char *) fbh->data; } } if (mysql_stmt_bind_result(imp_sth->stmt, imp_sth->buffer)) { do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); return 0; } } #endif imp_sth->done_desc= 1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_describe\n"); return TRUE; } /************************************************************************** * * Name: dbd_st_fetch * * Purpose: Called for fetching a result row * * Input: sth - statement handle being initialized * imp_sth - drivers private statement handle data * * Returns: array of columns; the array is allocated by DBI via * DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth), even the values * of the array are prepared, we just need to modify them * appropriately * **************************************************************************/ AV* dbd_st_fetch(SV *sth, imp_sth_t* imp_sth) { dTHX; int num_fields, ChopBlanks, i, rc; unsigned long *lengths; AV *av; int av_length, av_readonly; MYSQL_ROW cols; D_imp_dbh_from_sth; MYSQL* svsock= imp_dbh->pmysql; imp_sth_fbh_t *fbh; D_imp_xxh(sth); #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION MYSQL_BIND *buffer; #endif MYSQL_FIELD *fields; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> dbd_st_fetch\n"); #if MYSQL_ASYNC if(imp_dbh->async_query_in_flight) { if(mysql_db_async_result(sth, &imp_sth->result) <= 0) { return Nullav; } } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (!DBIc_ACTIVE(imp_sth) ) { do_error(sth, JW_ERR_SEQUENCE, "no statement executing\n",NULL); return Nullav; } if (imp_sth->fetch_done) { do_error(sth, JW_ERR_SEQUENCE, "fetch() but fetch already done",NULL); return Nullav; } if (!imp_sth->done_desc) { if (!dbd_describe(sth, imp_sth)) { do_error(sth, JW_ERR_SEQUENCE, "Error while describe result set.", NULL); return Nullav; } } } #endif ChopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch for %p, chopblanks %d\n", sth, ChopBlanks); if (!imp_sth->result) { do_error(sth, JW_ERR_SEQUENCE, "fetch() without execute()" ,NULL); return Nullav; } /* fix from 2.9008 */ imp_dbh->pmysql->net.last_errno = 0; #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch calling mysql_fetch\n"); if ((rc= mysql_stmt_fetch(imp_sth->stmt))) { if (rc == 1) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); #if MYSQL_VERSION_ID >= MYSQL_VERSION_5_0 if (rc == MYSQL_DATA_TRUNCATED) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch data truncated\n"); goto process; } #endif if (rc == MYSQL_NO_DATA) { /* Update row_num to affected_rows value */ imp_sth->row_num= mysql_stmt_affected_rows(imp_sth->stmt); imp_sth->fetch_done=1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch no data\n"); } dbd_st_finish(sth, imp_sth); return Nullav; } process: imp_sth->currow++; av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); num_fields=mysql_stmt_field_count(imp_sth->stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch called mysql_fetch, rc %d num_fields %d\n", rc, num_fields); for ( buffer= imp_sth->buffer, fbh= imp_sth->fbh, i= 0; i < num_fields; i++, fbh++, buffer++ ) { SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ STRLEN len; /* This is wrong, null is not being set correctly * This is not the way to determine length (this would break blobs!) */ if (fbh->is_null) (void) SvOK_off(sv); /* Field is NULL, return undef */ else { /* In case of BLOB/TEXT fields we allocate only 8192 bytes in dbd_describe() for data. Here we know real size of field so we should increase buffer size and refetch column value */ if (fbh->length > buffer->buffer_length || fbh->error) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tRefetch BLOB/TEXT column: %d, length: %lu, error: %d\n", i, fbh->length, fbh->error); Renew(fbh->data, fbh->length, char); buffer->buffer_length= fbh->length; buffer->buffer= (char *) fbh->data; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tbefore buffer->buffer: "); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n"); } /*TODO: Use offset instead of 0 to fetch only remain part of data*/ if (mysql_stmt_fetch_column(imp_sth->stmt, buffer , i, 0)) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tafter buffer->buffer: "); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n"); } } /* This does look a lot like Georg's PHP driver doesn't it? --Brian */ /* Credit due to Georg - mysqli_api.c ;) --PMG */ switch (buffer->buffer_type) { case MYSQL_TYPE_DOUBLE: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch double data %f\n", fbh->ddata); sv_setnv(sv, fbh->ddata); break; case MYSQL_TYPE_LONG: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch int data %"IVdf", unsigned? %d\n", fbh->ldata, buffer->is_unsigned); if (buffer->is_unsigned) sv_setuv(sv, fbh->ldata); else sv_setiv(sv, fbh->ldata); break; case MYSQL_TYPE_BIT: sv_setpvn(sv, fbh->data, fbh->length); break; default: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tERROR IN st_fetch_string"); len= fbh->length; /* ChopBlanks server-side prepared statement */ if (ChopBlanks) { /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if (fbh->charsetnr != 63) while (len && fbh->data[len-1] == ' ') { --len; } } /* END OF ChopBlanks */ sv_setpvn(sv, fbh->data, len); /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID >= FIELD_CHARSETNR_VERSION /* SHOW COLLATION WHERE Id = 63; -- 63 == charset binary, collation binary */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fbh->charsetnr != 63) #else if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && !(fbh->flags & BINARY_FLAG)) #endif sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields); return av; } else { #endif imp_sth->currow++; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch result set details\n"); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\timp_sth->result=%p\n", imp_sth->result); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_fields=%u\n", mysql_num_fields(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_rows=%llu\n", mysql_num_rows(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_affected_rows=%llu\n", mysql_affected_rows(imp_dbh->pmysql)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch for %p, currow= %d\n", sth,imp_sth->currow); } if (!(cols= mysql_fetch_row(imp_sth->result))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch, no more rows to fetch"); } if (mysql_errno(imp_dbh->pmysql)) do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if (!mysql_more_results(svsock)) #endif dbd_st_finish(sth, imp_sth); return Nullav; } num_fields= mysql_num_fields(imp_sth->result); fields= mysql_fetch_fields(imp_sth->result); lengths= mysql_fetch_lengths(imp_sth->result); if ((av= DBIc_FIELDS_AV(imp_sth)) != Nullav) { av_length= av_len(av)+1; if (av_length != num_fields) /* Resize array if necessary */ { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, size of results array(%d) != num_fields(%d)\n", av_length, num_fields); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, result fields(%d)\n", DBIc_NUM_FIELDS(imp_sth)); av_readonly = SvREADONLY(av); if (av_readonly) SvREADONLY_off( av ); /* DBI sets this readonly */ while (av_length < num_fields) { av_store(av, av_length++, newSV(0)); } while (av_length > num_fields) { SvREFCNT_dec(av_pop(av)); av_length--; } if (av_readonly) SvREADONLY_on(av); } } av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); for (i= 0; i < num_fields; ++i) { char *col= cols[i]; SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ if (col) { STRLEN len= lengths[i]; if (ChopBlanks) { while (len && col[len-1] == ' ') { --len; } } /* Set string value returned from mysql server */ sv_setpvn(sv, col, len); switch (mysql_to_perl_type(fields[i].type)) { case MYSQL_TYPE_DOUBLE: /* Coerce to dobule and set scalar as NV */ (void) SvNV(sv); SvNOK_only(sv); break; case MYSQL_TYPE_LONG: /* Coerce to integer and set scalar as UV resp. IV */ if (fields[i].flags & UNSIGNED_FLAG) { (void) SvUV(sv); SvIOK_only_UV(sv); } else { (void) SvIV(sv); SvIOK_only(sv); } break; #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_BIT: /* Let it as binary string */ break; #endif default: /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fields[i].charsetnr != 63) sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } else (void) SvOK_off(sv); /* Field is NULL, return undef */ } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields); return av; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION } #endif } #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* We have to fetch all data from stmt There is may be useful for 2 cases: 1. st_finish when we have undef statement 2. call st_execute again when we have some unfetched data in stmt */ int mysql_st_clean_cursor(SV* sth, imp_sth_t* imp_sth) { if (DBIc_ACTIVE(imp_sth) && dbd_describe(sth, imp_sth) && !imp_sth->fetch_done) mysql_stmt_free_result(imp_sth->stmt); return 1; } #endif /*************************************************************************** * * Name: dbd_st_finish * * Purpose: Called for freeing a mysql result * * Input: sth - statement handle being finished * imp_sth - drivers private statement handle data * * Returns: TRUE for success, FALSE otherwise; do_error() will * be called in the latter case * **************************************************************************/ int dbd_st_finish(SV* sth, imp_sth_t* imp_sth) { dTHX; D_imp_xxh(sth); #if defined (dTHR) dTHR; #endif #if MYSQL_ASYNC D_imp_dbh_from_sth; if(imp_dbh->async_query_in_flight) { mysql_db_async_result(sth, &imp_sth->result); } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n--> dbd_st_finish\n"); } if (imp_sth->use_server_side_prepare) { if (imp_sth && imp_sth->stmt) { if (!mysql_st_clean_cursor(sth, imp_sth)) { do_error(sth, JW_ERR_SEQUENCE, "Error happened while tried to clean up stmt",NULL); return 0; } } } #endif /* Cancel further fetches from this cursor. We don't close the cursor till DESTROY. The application may re execute it. */ if (imp_sth && DBIc_ACTIVE(imp_sth)) { /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets(sth, imp_sth); } DBIc_ACTIVE_off(imp_sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n<-- dbd_st_finish\n"); } return 1; } /************************************************************************** * * Name: dbd_st_destroy * * Purpose: Our part of the statement handles destructor * * Input: sth - statement handle being destroyed * imp_sth - drivers private statement handle data * * Returns: Nothing * **************************************************************************/ void dbd_st_destroy(SV *sth, imp_sth_t *imp_sth) { dTHX; D_imp_xxh(sth); #if defined (dTHR) dTHR; #endif int i; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION imp_sth_fbh_t *fbh; int n; n= DBIc_NUM_PARAMS(imp_sth); if (n) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tFreeing %d parameters, bind %p fbind %p\n", n, imp_sth->bind, imp_sth->fbind); free_bind(imp_sth->bind); free_fbind(imp_sth->fbind); } fbh= imp_sth->fbh; if (fbh) { n = DBIc_NUM_FIELDS(imp_sth); i = 0; while (i < n) { if (fbh[i].data) Safefree(fbh[i].data); ++i; } free_fbuffer(fbh); if (imp_sth->buffer) free_bind(imp_sth->buffer); } if (imp_sth->stmt) { if (mysql_stmt_close(imp_sth->stmt)) { do_error(DBIc_PARENT_H(imp_sth), mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); } } #endif /* dbd_st_finish has already been called by .xs code if needed. */ /* Free values allocated by dbd_bind_ph */ if (imp_sth->params) { free_param(aTHX_ imp_sth->params, DBIc_NUM_PARAMS(imp_sth)); imp_sth->params= NULL; } /* Free cached array attributes */ for (i= 0; i < AV_ATTRIB_LAST; i++) { if (imp_sth->av_attr[i]) SvREFCNT_dec(imp_sth->av_attr[i]); imp_sth->av_attr[i]= Nullav; } /* let DBI know we've done it */ DBIc_IMPSET_off(imp_sth); } /* ************************************************************************** * * Name: dbd_st_STORE_attrib * * Purpose: Modifies a statement handles attributes; we currently * support just nothing * * Input: sth - statement handle being destroyed * imp_sth - drivers private statement handle data * keysv - attribute name * valuesv - attribute value * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_STORE_attrib( SV *sth, imp_sth_t *imp_sth, SV *keysv, SV *valuesv ) { dTHX; STRLEN(kl); char *key= SvPV(keysv, kl); int retval= FALSE; D_imp_xxh(sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t-> dbd_st_STORE_attrib for %p, key %s\n", sth, key); if (strEQ(key, "mysql_use_result")) { imp_sth->use_mysql_use_result= SvTRUE(valuesv); } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t<- dbd_st_STORE_attrib for %p, result %d\n", sth, retval); return retval; } /* ************************************************************************** * * Name: dbd_st_FETCH_internal * * Purpose: Retrieves a statement handles array attributes; we use * a separate function, because creating the array * attributes shares much code and it aids in supporting * enhanced features like caching. * * Input: sth - statement handle; may even be a database handle, * in which case this will be used for storing error * messages only. This is only valid, if cacheit (the * last argument) is set to TRUE. * what - internal attribute number * res - pointer to a DBMS result * cacheit - TRUE, if results may be cached in the sth. * * Returns: RV pointing to result array in case of success, NULL * otherwise; do_error has already been called in the latter * case. * **************************************************************************/ #ifndef IS_KEY #define IS_KEY(A) (((A) & (PRI_KEY_FLAG | UNIQUE_KEY_FLAG | MULTIPLE_KEY_FLAG)) != 0) #endif #if !defined(IS_AUTO_INCREMENT) && defined(AUTO_INCREMENT_FLAG) #define IS_AUTO_INCREMENT(A) (((A) & AUTO_INCREMENT_FLAG) != 0) #endif SV* dbd_st_FETCH_internal( SV *sth, int what, MYSQL_RES *res, int cacheit ) { dTHX; D_imp_sth(sth); AV *av= Nullav; MYSQL_FIELD *curField; /* Are we asking for a legal value? */ if (what < 0 || what >= AV_ATTRIB_LAST) do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Not implemented", NULL); /* Return cached value, if possible */ else if (cacheit && imp_sth->av_attr[what]) av= imp_sth->av_attr[what]; /* Does this sth really have a result? */ else if (!res) do_error(sth, JW_ERR_NOT_ACTIVE, "statement contains no result" ,NULL); /* Do the real work. */ else { av= newAV(); mysql_field_seek(res, 0); while ((curField= mysql_fetch_field(res))) { SV *sv; switch(what) { case AV_ATTRIB_NAME: sv= newSVpvn(curField->name, strlen(curField->name)); break; case AV_ATTRIB_TABLE: sv= newSVpvn(curField->table, strlen(curField->table)); break; case AV_ATTRIB_TYPE: sv= newSViv((int) curField->type); break; case AV_ATTRIB_SQL_TYPE: sv= newSViv((int) native2sql(curField->type)->data_type); break; case AV_ATTRIB_IS_PRI_KEY: sv= boolSV(IS_PRI_KEY(curField->flags)); break; case AV_ATTRIB_IS_NOT_NULL: sv= boolSV(IS_NOT_NULL(curField->flags)); break; case AV_ATTRIB_NULLABLE: sv= boolSV(!IS_NOT_NULL(curField->flags)); break; case AV_ATTRIB_LENGTH: sv= newSViv((int) curField->length); break; case AV_ATTRIB_IS_NUM: sv= newSViv((int) native2sql(curField->type)->is_num); break; case AV_ATTRIB_TYPE_NAME: sv= newSVpv((char*) native2sql(curField->type)->type_name, 0); break; case AV_ATTRIB_MAX_LENGTH: sv= newSViv((int) curField->max_length); break; case AV_ATTRIB_IS_AUTO_INCREMENT: #if defined(AUTO_INCREMENT_FLAG) sv= boolSV(IS_AUTO_INCREMENT(curField->flags)); break; #else croak("AUTO_INCREMENT_FLAG is not supported on this machine"); #endif case AV_ATTRIB_IS_KEY: sv= boolSV(IS_KEY(curField->flags)); break; case AV_ATTRIB_IS_BLOB: sv= boolSV(IS_BLOB(curField->flags)); break; case AV_ATTRIB_SCALE: sv= newSViv((int) curField->decimals); break; case AV_ATTRIB_PRECISION: sv= newSViv((int) (curField->length > curField->max_length) ? curField->length : curField->max_length); break; default: sv= &PL_sv_undef; break; } av_push(av, sv); } /* Ensure that this value is kept, decremented in * dbd_st_destroy and dbd_st_execute. */ if (!cacheit) return sv_2mortal(newRV_noinc((SV*)av)); imp_sth->av_attr[what]= av; } if (av == Nullav) return &PL_sv_undef; return sv_2mortal(newRV_inc((SV*)av)); } /* ************************************************************************** * * Name: dbd_st_FETCH_attrib * * Purpose: Retrieves a statement handles attributes * * Input: sth - statement handle being destroyed * imp_sth - drivers private statement handle data * keysv - attribute name * * Returns: NULL for an unknown attribute, "undef" for error, * attribute value otherwise. * **************************************************************************/ #define ST_FETCH_AV(what) \ dbd_st_FETCH_internal(sth, (what), imp_sth->result, TRUE) SV* dbd_st_FETCH_attrib( SV *sth, imp_sth_t *imp_sth, SV *keysv ) { dTHX; STRLEN(kl); char *key= SvPV(keysv, kl); SV *retsv= Nullsv; D_imp_xxh(sth); if (kl < 2) return Nullsv; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " -> dbd_st_FETCH_attrib for %p, key %s\n", sth, key); switch (*key) { case 'N': if (strEQ(key, "NAME")) retsv= ST_FETCH_AV(AV_ATTRIB_NAME); else if (strEQ(key, "NULLABLE")) retsv= ST_FETCH_AV(AV_ATTRIB_NULLABLE); break; case 'P': if (strEQ(key, "PRECISION")) retsv= ST_FETCH_AV(AV_ATTRIB_PRECISION); if (strEQ(key, "ParamValues")) { HV *pvhv= newHV(); if (DBIc_NUM_PARAMS(imp_sth)) { int n; char key[100]; I32 keylen; for (n= 0; n < DBIc_NUM_PARAMS(imp_sth); n++) { keylen= sprintf(key, "%d", n); (void)hv_store(pvhv, key, keylen, newSVsv(imp_sth->params[n].value), 0); } } retsv= sv_2mortal(newRV_noinc((SV*)pvhv)); } break; case 'S': if (strEQ(key, "SCALE")) retsv= ST_FETCH_AV(AV_ATTRIB_SCALE); break; case 'T': if (strEQ(key, "TYPE")) retsv= ST_FETCH_AV(AV_ATTRIB_SQL_TYPE); break; case 'm': switch (kl) { case 10: if (strEQ(key, "mysql_type")) retsv= ST_FETCH_AV(AV_ATTRIB_TYPE); break; case 11: if (strEQ(key, "mysql_table")) retsv= ST_FETCH_AV(AV_ATTRIB_TABLE); break; case 12: if ( strEQ(key, "mysql_is_key")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_KEY); else if (strEQ(key, "mysql_is_num")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_NUM); else if (strEQ(key, "mysql_length")) retsv= ST_FETCH_AV(AV_ATTRIB_LENGTH); else if (strEQ(key, "mysql_result")) retsv= sv_2mortal(newSViv(PTR2IV(imp_sth->result))); break; case 13: if (strEQ(key, "mysql_is_blob")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_BLOB); break; case 14: if (strEQ(key, "mysql_insertid")) { /* We cannot return an IV, because the insertid is a long. */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "INSERT ID %llu\n", imp_sth->insertid); return sv_2mortal(my_ulonglong2str(aTHX_ imp_sth->insertid)); } break; case 15: if (strEQ(key, "mysql_type_name")) retsv = ST_FETCH_AV(AV_ATTRIB_TYPE_NAME); break; case 16: if ( strEQ(key, "mysql_is_pri_key")) retsv= ST_FETCH_AV(AV_ATTRIB_IS_PRI_KEY); else if (strEQ(key, "mysql_max_length")) retsv= ST_FETCH_AV(AV_ATTRIB_MAX_LENGTH); else if (strEQ(key, "mysql_use_result")) retsv= boolSV(imp_sth->use_mysql_use_result); break; case 19: if (strEQ(key, "mysql_warning_count")) retsv= sv_2mortal(newSViv((IV) imp_sth->warning_count)); break; case 20: if (strEQ(key, "mysql_server_prepare")) #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION retsv= sv_2mortal(newSViv((IV) imp_sth->use_server_side_prepare)); #else retsv= boolSV(0); #endif break; case 23: if (strEQ(key, "mysql_is_auto_increment")) retsv = ST_FETCH_AV(AV_ATTRIB_IS_AUTO_INCREMENT); break; } break; } return retsv; } /*************************************************************************** * * Name: dbd_st_blob_read * * Purpose: Used for blob reads if the statement handles "LongTruncOk" * attribute (currently not supported by DBD::mysql) * * Input: SV* - statement handle from which a blob will be fetched * imp_sth - drivers private statement handle data * field - field number of the blob (note, that a row may * contain more than one blob) * offset - the offset of the field, where to start reading * len - maximum number of bytes to read * destrv - RV* that tells us where to store * destoffset - destination offset * * Returns: TRUE for success, FALSE otherwise; do_error will * be called in the latter case * **************************************************************************/ int dbd_st_blob_read ( SV *sth, imp_sth_t *imp_sth, int field, long offset, long len, SV *destrv, long destoffset) { /* quell warnings */ sth= sth; imp_sth=imp_sth; field= field; offset= offset; len= len; destrv= destrv; destoffset= destoffset; return FALSE; } /*************************************************************************** * * Name: dbd_bind_ph * * Purpose: Binds a statement value to a parameter * * Input: sth - statement handle * imp_sth - drivers private statement handle data * param - parameter number, counting starts with 1 * value - value being inserted for parameter "param" * sql_type - SQL type of the value * attribs - bind parameter attributes, currently this must be * one of the values SQL_CHAR, ... * inout - TRUE, if parameter is an output variable (currently * this is not supported) * maxlen - ??? * * Returns: TRUE for success, FALSE otherwise * **************************************************************************/ int dbd_bind_ph(SV *sth, imp_sth_t *imp_sth, SV *param, SV *value, IV sql_type, SV *attribs, int is_inout, IV maxlen) { dTHX; int rc; int param_num= SvIV(param); int idx= param_num - 1; char *err_msg; D_imp_xxh(sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION STRLEN slen; char *buffer= NULL; int buffer_is_null= 0; int buffer_length= slen; unsigned int buffer_type= 0; #endif D_imp_dbh_from_sth; ASYNC_CHECK_RETURN(sth, FALSE); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " Called: dbd_bind_ph\n"); attribs= attribs; maxlen= maxlen; if (param_num <= 0 || param_num > DBIc_NUM_PARAMS(imp_sth)) { do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, "Illegal parameter number", NULL); return FALSE; } /* This fixes the bug whereby no warning was issued upon binding a defined non-numeric as numeric */ if (SvOK(value) && (sql_type == SQL_NUMERIC || sql_type == SQL_DECIMAL || sql_type == SQL_INTEGER || sql_type == SQL_SMALLINT || sql_type == SQL_FLOAT || sql_type == SQL_REAL || sql_type == SQL_DOUBLE) ) { if (! looks_like_number(value)) { err_msg = SvPVX(sv_2mortal(newSVpvf( "Binding non-numeric field %d, value %s as a numeric!", param_num, neatsvpv(value,0)))); do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, err_msg, NULL); } } if (is_inout) { do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Output parameters not implemented", NULL); return FALSE; } rc = bind_param(&imp_sth->params[idx], value, sql_type); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { switch(sql_type) { case SQL_NUMERIC: case SQL_INTEGER: case SQL_SMALLINT: case SQL_BIGINT: case SQL_TINYINT: buffer_type= MYSQL_TYPE_LONG; break; case SQL_DOUBLE: case SQL_DECIMAL: case SQL_FLOAT: case SQL_REAL: buffer_type= MYSQL_TYPE_DOUBLE; break; case SQL_CHAR: case SQL_VARCHAR: case SQL_DATE: case SQL_TIME: case SQL_TIMESTAMP: case SQL_LONGVARCHAR: case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: buffer_type= MYSQL_TYPE_BLOB; break; default: buffer_type= MYSQL_TYPE_STRING; } buffer_is_null = !(SvOK(imp_sth->params[idx].value) && imp_sth->params[idx].value); if (! buffer_is_null) { switch(buffer_type) { case MYSQL_TYPE_LONG: /* INT */ if (!SvIOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND AN INT NUMBER\n"); buffer_length = sizeof imp_sth->fbind[idx].numeric_val.lval; imp_sth->fbind[idx].numeric_val.lval= SvIV(imp_sth->params[idx].value); buffer=(void*)&(imp_sth->fbind[idx].numeric_val.lval); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type %"IVdf" ->%"IVdf"<- IS A INT NUMBER\n", sql_type, *(IV *)buffer); break; case MYSQL_TYPE_DOUBLE: if (!SvNOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND A FLOAT NUMBER\n"); buffer_length = sizeof imp_sth->fbind[idx].numeric_val.dval; imp_sth->fbind[idx].numeric_val.dval= SvNV(imp_sth->params[idx].value); buffer=(char*)&(imp_sth->fbind[idx].numeric_val.dval); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type %"IVdf" ->%f<- IS A FLOAT NUMBER\n", sql_type, (double)(*buffer)); break; case MYSQL_TYPE_BLOB: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type BLOB\n"); break; case MYSQL_TYPE_STRING: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type STRING %"IVdf", buffertype=%d\n", sql_type, buffer_type); break; default: croak("Bug in DBD::Mysql file dbdimp.c#dbd_bind_ph: do not know how to handle unknown buffer type."); } if (buffer_type == MYSQL_TYPE_STRING || buffer_type == MYSQL_TYPE_BLOB) { buffer= SvPV(imp_sth->params[idx].value, slen); buffer_length= slen; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR type %"IVdf" ->length %d<- IS A STRING or BLOB\n", sql_type, buffer_length); } } else { /*case: buffer_is_null != 0*/ buffer= NULL; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " SCALAR NULL VALUE: buffer type is: %d\n", buffer_type); } /* Type of column was changed. Force to rebind */ if (imp_sth->bind[idx].buffer_type != buffer_type) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), " FORCE REBIND: buffer type changed from %d to %d, sql-type=%"IVdf"\n", (int) imp_sth->bind[idx].buffer_type, buffer_type, sql_type); imp_sth->has_been_bound = 0; } /* prepare has been called */ if (imp_sth->has_been_bound) { imp_sth->stmt->params[idx].buffer= buffer; imp_sth->stmt->params[idx].buffer_length= buffer_length; } imp_sth->bind[idx].buffer_type= buffer_type; imp_sth->bind[idx].buffer= buffer; imp_sth->bind[idx].buffer_length= buffer_length; imp_sth->fbind[idx].length= buffer_length; imp_sth->fbind[idx].is_null= buffer_is_null; } #endif return rc; } /*************************************************************************** * * Name: mysql_db_reconnect * * Purpose: If the server has disconnected, try to reconnect. * * Input: h - database or statement handle * * Returns: TRUE for success, FALSE otherwise * **************************************************************************/ int mysql_db_reconnect(SV* h) { dTHX; D_imp_xxh(h); imp_dbh_t* imp_dbh; MYSQL save_socket; if (DBIc_TYPE(imp_xxh) == DBIt_ST) { imp_dbh = (imp_dbh_t*) DBIc_PARENT_COM(imp_xxh); h = DBIc_PARENT_H(imp_xxh); } else imp_dbh= (imp_dbh_t*) imp_xxh; if (mysql_errno(imp_dbh->pmysql) != CR_SERVER_GONE_ERROR) /* Other error */ return FALSE; if (!DBIc_has(imp_dbh, DBIcf_AutoCommit) || !imp_dbh->auto_reconnect) { /* We never reconnect if AutoCommit is turned off. * Otherwise we might get an inconsistent transaction * state. */ return FALSE; } /* my_login will blow away imp_dbh->mysql so we save a copy of * imp_dbh->mysql and put it back where it belongs if the reconnect * fail. Think server is down & reconnect fails but the application eval{}s * the execute, so next time $dbh->quote() gets called, instant SIGSEGV! */ save_socket= *(imp_dbh->pmysql); memcpy (&save_socket, imp_dbh->pmysql,sizeof(save_socket)); memset (imp_dbh->pmysql,0,sizeof(*(imp_dbh->pmysql))); /* we should disconnect the db handle before reconnecting, this will * prevent my_login from thinking it's adopting an active child which * would prevent the handle from actually reconnecting */ if (!dbd_db_disconnect(h, imp_dbh) || !my_login(aTHX_ h, imp_dbh)) { do_error(h, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); memcpy (imp_dbh->pmysql, &save_socket, sizeof(save_socket)); ++imp_dbh->stats.auto_reconnects_failed; return FALSE; } /* * Tell DBI, that dbh->disconnect should be called for this handle */ DBIc_ACTIVE_on(imp_dbh); ++imp_dbh->stats.auto_reconnects_ok; return TRUE; } /************************************************************************** * * Name: dbd_db_type_info_all * * Purpose: Implements $dbh->type_info_all * * Input: dbh - database handle * imp_sth - drivers private database handle data * * Returns: RV to AV of types * **************************************************************************/ #define PV_PUSH(c) \ if (c) { \ sv= newSVpv((char*) (c), 0); \ SvREADONLY_on(sv); \ } else { \ sv= &PL_sv_undef; \ } \ av_push(row, sv); #define IV_PUSH(i) sv= newSViv((i)); SvREADONLY_on(sv); av_push(row, sv); AV *dbd_db_type_info_all(SV *dbh, imp_dbh_t *imp_dbh) { dTHX; AV *av= newAV(); AV *row; HV *hv; SV *sv; int i; const char *cols[] = { "TYPE_NAME", "DATA_TYPE", "COLUMN_SIZE", "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS", "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE", "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_UNIQUE_VALUE", "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE", "NUM_PREC_RADIX", "SQL_DATATYPE", "SQL_DATETIME_SUB", "INTERVAL_PRECISION", "mysql_native_type", "mysql_is_num" }; dbh= dbh; imp_dbh= imp_dbh; hv= newHV(); av_push(av, newRV_noinc((SV*) hv)); for (i= 0; i < (int)(sizeof(cols) / sizeof(const char*)); i++) { if (!hv_store(hv, (char*) cols[i], strlen(cols[i]), newSViv(i), 0)) { SvREFCNT_dec((SV*) av); return Nullav; } } for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++) { const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i]; row= newAV(); av_push(av, newRV_noinc((SV*) row)); PV_PUSH(t->type_name); IV_PUSH(t->data_type); IV_PUSH(t->column_size); PV_PUSH(t->literal_prefix); PV_PUSH(t->literal_suffix); PV_PUSH(t->create_params); IV_PUSH(t->nullable); IV_PUSH(t->case_sensitive); IV_PUSH(t->searchable); IV_PUSH(t->unsigned_attribute); IV_PUSH(t->fixed_prec_scale); IV_PUSH(t->auto_unique_value); PV_PUSH(t->local_type_name); IV_PUSH(t->minimum_scale); IV_PUSH(t->maximum_scale); if (t->num_prec_radix) { IV_PUSH(t->num_prec_radix); } else av_push(row, &PL_sv_undef); IV_PUSH(t->sql_datatype); /* SQL_DATATYPE*/ IV_PUSH(t->sql_datetime_sub); /* SQL_DATETIME_SUB*/ IV_PUSH(t->interval_precision); /* INTERVAL_PERCISION */ IV_PUSH(t->native_type); IV_PUSH(t->is_num); } return av; } /* dbd_db_quote Properly quotes a value */ SV* dbd_db_quote(SV *dbh, SV *str, SV *type) { dTHX; SV *result; if (SvGMAGICAL(str)) mg_get(str); if (!SvOK(str)) result= newSVpvn("NULL", 4); else { char *ptr, *sptr; STRLEN len; D_imp_dbh(dbh); if (type && SvMAGICAL(type)) mg_get(type); if (type && SvOK(type)) { int i; int tp= SvIV(type); for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++) { const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i]; if (t->data_type == tp) { if (!t->literal_prefix) return Nullsv; break; } } } ptr= SvPV(str, len); result= newSV(len*2+3); #ifdef SvUTF8 if (SvUTF8(str)) SvUTF8_on(result); #endif sptr= SvPVX(result); *sptr++ = '\''; sptr+= mysql_real_escape_string(imp_dbh->pmysql, sptr, ptr, len); *sptr++= '\''; SvPOK_on(result); SvCUR_set(result, sptr - SvPVX(result)); /* Never hurts NUL terminating a Per string */ *sptr++= '\0'; } return result; } #ifdef DBD_MYSQL_INSERT_ID_IS_GOOD SV *mysql_db_last_insert_id(SV *dbh, imp_dbh_t *imp_dbh, SV *catalog, SV *schema, SV *table, SV *field, SV *attr) { dTHX; /* all these non-op settings are to stifle OS X compile warnings */ imp_dbh= imp_dbh; dbh= dbh; catalog= catalog; schema= schema; table= table; field= field; attr= attr; ASYNC_CHECK_RETURN(dbh, &PL_sv_undef); return sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql))); } #endif #if MYSQL_ASYNC int mysql_db_async_result(SV* h, MYSQL_RES** resp) { dTHX; D_imp_xxh(h); imp_dbh_t* dbh; MYSQL* svsock = NULL; MYSQL_RES* _res; int retval = 0; int htype; if(! resp) { resp = &_res; } htype = DBIc_TYPE(imp_xxh); if(htype == DBIt_DB) { D_imp_dbh(h); dbh = imp_dbh; } else { D_imp_sth(h); D_imp_dbh_from_sth; dbh = imp_dbh; } if(! dbh->async_query_in_flight) { do_error(h, 2000, "Gathering asynchronous results for a synchronous handle", "HY000"); return -1; } if(dbh->async_query_in_flight != imp_xxh) { do_error(h, 2000, "Gathering async_query_in_flight results for the wrong handle", "HY000"); return -1; } dbh->async_query_in_flight = NULL; svsock= dbh->pmysql; retval= mysql_read_query_result(svsock); if(! retval) { *resp= mysql_store_result(svsock); if (mysql_errno(svsock)) do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); if (!*resp) retval= mysql_affected_rows(svsock); else { retval= mysql_num_rows(*resp); if(resp == &_res) { mysql_free_result(*resp); } } if(htype == DBIt_ST) { D_imp_sth(h); D_imp_dbh_from_sth; if((my_ulonglong)retval+1 != (my_ulonglong)-1) { if(! *resp) { imp_sth->insertid= mysql_insert_id(svsock); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if(! mysql_more_results(svsock)) DBIc_ACTIVE_off(imp_sth); #endif } else { DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result); imp_sth->done_desc= 0; imp_sth->fetch_done= 0; } } imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql); } } else { do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock)); return -1; } return retval; } int mysql_db_async_ready(SV* h) { dTHX; D_imp_xxh(h); imp_dbh_t* dbh; int htype; htype = DBIc_TYPE(imp_xxh); if(htype == DBIt_DB) { D_imp_dbh(h); dbh = imp_dbh; } else { D_imp_sth(h); D_imp_dbh_from_sth; dbh = imp_dbh; } if(dbh->async_query_in_flight) { if(dbh->async_query_in_flight == imp_xxh) { struct pollfd fds; int retval; fds.fd = dbh->pmysql->net.fd; fds.events = POLLIN; retval = poll(&fds, 1, 0); if(retval < 0) { do_error(h, errno, strerror(errno), "HY000"); } return retval; } else { do_error(h, 2000, "Calling mysql_async_ready on the wrong handle", "HY000"); return -1; } } else { do_error(h, 2000, "Handle is not in asynchronous mode", "HY000"); return -1; } } #endif static int parse_number(char *string, STRLEN len, char **end) { int seen_neg; int seen_dec; int seen_e; int seen_plus; int seen_digit; char *cp; seen_neg= seen_dec= seen_e= seen_plus= seen_digit= 0; if (len <= 0) { len= strlen(string); } cp= string; /* Skip leading whitespace */ while (*cp && isspace(*cp)) cp++; for ( ; *cp; cp++) { if ('-' == *cp) { if (seen_neg >= 2) { /* third '-'. number can contains two '-'. because -1e-10 is valid number */ break; } seen_neg += 1; } else if ('.' == *cp) { if (seen_dec) { /* second '.' */ break; } seen_dec= 1; } else if ('e' == *cp) { if (seen_e) { /* second 'e' */ break; } seen_e= 1; } else if ('+' == *cp) { if (seen_plus) { /* second '+' */ break; } seen_plus= 1; } else if (!isdigit(*cp)) { /* Not sure why this was changed */ /* seen_digit= 1; */ break; } } *end= cp; /* length 0 -> not a number */ /* Need to revisit this */ /*if (len == 0 || cp - string < (int) len || seen_digit == 0) {*/ if (len == 0 || cp - string < (int) len) { return -1; } return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_4901_1
crossvul-cpp_data_good_4493_0
/************************************************************************* * * $Id: trio.c,v 1.131 2010/09/12 11:08:08 breese Exp $ * * Copyright (C) 1998, 2009 Bjorn Reese and Daniel Stenberg. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. * ************************************************************************* * * A note to trio contributors: * * Avoid heap allocation at all costs to ensure that the trio functions * are async-safe. The exceptions are the printf/fprintf functions, which * uses fputc, and the asprintf functions and the <alloc> modifier, which * by design are required to allocate form the heap. * ************************************************************************/ /* * TODO: * - Scan is probably too permissive about its modifiers. * - C escapes in %#[] ? * - Multibyte characters (done for format parsing, except scan groups) * - Complex numbers? (C99 _Complex) * - Boolean values? (C99 _Bool) * - C99 NaN(n-char-sequence) missing. The n-char-sequence can be used * to print the mantissa, e.g. NaN(0xc000000000000000) * - Should we support the GNU %a alloc modifier? GNU has an ugly hack * for %a, because C99 used %a for other purposes. If specified as * %as or %a[ it is interpreted as the alloc modifier, otherwise as * the C99 hex-float. This means that you cannot scan %as as a hex-float * immediately followed by an 's'. * - Scanning of collating symbols. */ /************************************************************************* * Trio include files */ #include "triodef.h" #include "trio.h" #include "triop.h" #if defined(TRIO_EMBED_NAN) #define TRIO_PUBLIC_NAN static #if TRIO_FEATURE_FLOAT #define TRIO_FUNC_NAN #define TRIO_FUNC_NINF #define TRIO_FUNC_PINF #define TRIO_FUNC_FPCLASSIFY_AND_SIGNBIT #define TRIO_FUNC_ISINF #endif #endif #include "trionan.h" #if defined(TRIO_EMBED_STRING) #define TRIO_PUBLIC_STRING static #define TRIO_FUNC_LENGTH #define TRIO_FUNC_LENGTH_MAX #define TRIO_FUNC_TO_LONG #if TRIO_FEATURE_LOCALE #define TRIO_FUNC_COPY_MAX #endif #if TRIO_FEATURE_DYNAMICSTRING #define TRIO_FUNC_XSTRING_DUPLICATE #endif #if TRIO_EXTENSION && TRIO_FEATURE_SCANF #define TRIO_FUNC_EQUAL_LOCALE #endif #if TRIO_FEATURE_ERRNO #define TRIO_FUNC_ERROR #endif #if TRIO_FEATURE_FLOAT && TRIO_FEATURE_SCANF #define TRIO_FUNC_TO_DOUBLE #endif #if TRIO_FEATURE_DYNAMICSTRING #define TRIO_FUNC_STRING_EXTRACT #endif #if TRIO_FEATURE_DYNAMICSTRING #define TRIO_FUNC_STRING_TERMINATE #endif #if TRIO_FEATURE_USER_DEFINED #define TRIO_FUNC_DUPLICATE #endif #if TRIO_FEATURE_DYNAMICSTRING #define TRIO_FUNC_STRING_DESTROY #endif #if TRIO_FEATURE_USER_DEFINED #define TRIO_FUNC_DESTROY #endif #if TRIO_FEATURE_USER_DEFINED || (TRIO_FEATURE_FLOAT && TRIO_FEATURE_SCANF) #define TRIO_FUNC_EQUAL #endif #if TRIO_FEATURE_USER_DEFINED || TRIO_FEATURE_SCANF #define TRIO_FUNC_EQUAL_CASE #endif #if (TRIO_EXTENSION && TRIO_FEATURE_SCANF) #define TRIO_FUNC_EQUAL_MAX #endif #if TRIO_FEATURE_SCANF #define TRIO_FUNC_TO_UPPER #endif #if TRIO_FEATURE_DYNAMICSTRING #define TRIO_FUNC_XSTRING_APPEND_CHAR #endif #endif #include "triostr.h" /************************************************************************** * * Definitions * *************************************************************************/ #include <limits.h> #if TRIO_FEATURE_FLOAT #include <math.h> #include <float.h> #endif #if defined(__STDC_ISO_10646__) || defined(MB_LEN_MAX) || defined(USE_MULTIBYTE) || \ TRIO_FEATURE_WIDECHAR #if (!defined(TRIO_PLATFORM_WINCE) && !defined(ANDROID)) #define TRIO_COMPILER_SUPPORTS_MULTIBYTE #if !defined(MB_LEN_MAX) #define MB_LEN_MAX 6 #endif #endif #endif #if (TRIO_COMPILER_VISUALC - 0 >= 1100) || defined(TRIO_COMPILER_BORLAND) #define TRIO_COMPILER_SUPPORTS_VISUALC_INT #endif #if TRIO_FEATURE_FLOAT #if defined(PREDEF_STANDARD_C99) || defined(PREDEF_STANDARD_UNIX03) #if !defined(HAVE_FLOORL) && !defined(TRIO_NO_FLOORL) #define HAVE_FLOORL #endif #if !defined(HAVE_CEILL) && !defined(TRIO_NO_CEILL) #define HAVE_CEILL #endif #if !defined(HAVE_POWL) && !defined(TRIO_NO_POWL) #define HAVE_POWL #endif #if !defined(HAVE_FMODL) && !defined(TRIO_NO_FMODL) #define HAVE_FMODL #endif #if !defined(HAVE_LOG10L) && !defined(TRIO_NO_LOG10L) #define HAVE_LOG10L #endif #endif #if defined(TRIO_COMPILER_VISUALC) #if defined(floorl) #define HAVE_FLOORL #endif #if defined(ceill) #define HAVE_CEILL #endif #if defined(powl) #define HAVE_POWL #endif #if defined(fmodl) #define HAVE_FMODL #endif #if defined(log10l) #define HAVE_LOG10L #endif #endif #endif /************************************************************************* * Generic definitions */ #if !(defined(DEBUG) || defined(NDEBUG)) #define NDEBUG #endif #include <assert.h> #include <ctype.h> #if defined(PREDEF_STANDARD_C99) && !defined(isascii) #define isascii(x) ((x)&0x7F) #endif #if defined(TRIO_COMPILER_ANCIENT) #include <varargs.h> #else #include <stdarg.h> #endif #include <stddef.h> #if defined(TRIO_PLATFORM_WINCE) extern int errno; #else #include <errno.h> #endif #ifndef NULL #define NULL 0 #endif #define NIL ((char)0) #ifndef FALSE #define FALSE (1 == 0) #define TRUE (!FALSE) #endif #define BOOLEAN_T int /* mincore() can be used for debugging purposes */ #define VALID(x) (NULL != (x)) #if TRIO_FEATURE_ERRORCODE /* * Encode the error code and the position. This is decoded * with TRIO_ERROR_CODE and TRIO_ERROR_POSITION. */ #define TRIO_ERROR_RETURN(x, y) (-((x) + ((y) << 8))) #else #define TRIO_ERROR_RETURN(x, y) (-1) #endif typedef unsigned long trio_flags_t; /************************************************************************* * Platform specific definitions */ #if defined(TRIO_PLATFORM_UNIX) #include <unistd.h> #include <signal.h> #include <locale.h> #if !defined(TRIO_FEATURE_LOCALE) #define USE_LOCALE #endif #endif /* TRIO_PLATFORM_UNIX */ #if defined(TRIO_PLATFORM_VMS) #include <unistd.h> #endif #if defined(TRIO_PLATFORM_WIN32) #if defined(TRIO_PLATFORM_WINCE) int read(int handle, char* buffer, unsigned int length); int write(int handle, const char* buffer, unsigned int length); #else #include <io.h> #define read _read #define write _write #endif #endif /* TRIO_PLATFORM_WIN32 */ #if TRIO_FEATURE_WIDECHAR #if defined(PREDEF_STANDARD_C94) #include <wchar.h> #include <wctype.h> typedef wchar_t trio_wchar_t; typedef wint_t trio_wint_t; #else typedef char trio_wchar_t; typedef int trio_wint_t; #define WCONST(x) L##x #define WEOF EOF #define iswalnum(x) isalnum(x) #define iswalpha(x) isalpha(x) #define iswcntrl(x) iscntrl(x) #define iswdigit(x) isdigit(x) #define iswgraph(x) isgraph(x) #define iswlower(x) islower(x) #define iswprint(x) isprint(x) #define iswpunct(x) ispunct(x) #define iswspace(x) isspace(x) #define iswupper(x) isupper(x) #define iswxdigit(x) isxdigit(x) #endif #endif /************************************************************************* * Compiler dependent definitions */ /* Support for long long */ #ifndef __cplusplus #if !defined(USE_LONGLONG) #if defined(TRIO_COMPILER_GCC) && !defined(__STRICT_ANSI__) #define USE_LONGLONG #else #if defined(TRIO_COMPILER_SUNPRO) #define USE_LONGLONG #else #if defined(TRIO_COMPILER_MSVC) && (_MSC_VER >= 1400) #define USE_LONGLONG #else #if defined(_LONG_LONG) || defined(_LONGLONG) #define USE_LONGLONG #endif #endif #endif #endif #endif #endif /* The extra long numbers */ #if defined(USE_LONGLONG) typedef signed long long int trio_longlong_t; typedef unsigned long long int trio_ulonglong_t; #else #if defined(TRIO_COMPILER_SUPPORTS_VISUALC_INT) typedef signed __int64 trio_longlong_t; typedef unsigned __int64 trio_ulonglong_t; #else typedef TRIO_SIGNED long int trio_longlong_t; typedef unsigned long int trio_ulonglong_t; #endif #endif /* Maximal and fixed integer types */ #if defined(PREDEF_STANDARD_C99) #include <stdint.h> typedef intmax_t trio_intmax_t; typedef uintmax_t trio_uintmax_t; typedef int8_t trio_int8_t; typedef int16_t trio_int16_t; typedef int32_t trio_int32_t; typedef int64_t trio_int64_t; #else #if defined(PREDEF_STANDARD_UNIX98) #include <inttypes.h> typedef intmax_t trio_intmax_t; typedef uintmax_t trio_uintmax_t; typedef int8_t trio_int8_t; typedef int16_t trio_int16_t; typedef int32_t trio_int32_t; typedef int64_t trio_int64_t; #else #if defined(TRIO_COMPILER_SUPPORTS_VISUALC_INT) typedef trio_longlong_t trio_intmax_t; typedef trio_ulonglong_t trio_uintmax_t; typedef __int8 trio_int8_t; typedef __int16 trio_int16_t; typedef __int32 trio_int32_t; typedef __int64 trio_int64_t; #else typedef trio_longlong_t trio_intmax_t; typedef trio_ulonglong_t trio_uintmax_t; #if defined(TRIO_INT8_T) typedef TRIO_INT8_T trio_int8_t; #else typedef TRIO_SIGNED char trio_int8_t; #endif #if defined(TRIO_INT16_T) typedef TRIO_INT16_T trio_int16_t; #else typedef TRIO_SIGNED short trio_int16_t; #endif #if defined(TRIO_INT32_T) typedef TRIO_INT32_T trio_int32_t; #else typedef TRIO_SIGNED int trio_int32_t; #endif #if defined(TRIO_INT64_T) typedef TRIO_INT64_T trio_int64_t; #else typedef trio_longlong_t trio_int64_t; #endif #endif #endif #endif #if defined(HAVE_FLOORL) #define trio_floor(x) floorl((x)) #else #define trio_floor(x) floor((double)(x)) #endif #if defined(HAVE_CEILL) #define trio_ceil(x) ceill((x)) #else #define trio_ceil(x) ceil((double)(x)) #endif #if defined(HAVE_FMODL) #define trio_fmod(x, y) fmodl((x), (y)) #else #define trio_fmod(x, y) fmod((double)(x), (double)(y)) #endif #if defined(HAVE_POWL) #define trio_pow(x, y) powl((x), (y)) #else #define trio_pow(x, y) pow((double)(x), (double)(y)) #endif #if defined(HAVE_LOG10L) #define trio_log10(x) log10l((x)) #else #define trio_log10(x) log10((double)(x)) #endif #if TRIO_FEATURE_FLOAT #define TRIO_FABS(x) (((x) < 0.0) ? -(x) : (x)) #endif /************************************************************************* * Internal Definitions */ #ifdef _WIN32 #pragma warning(push) #pragma warning(disable : 4244) #endif #if TRIO_FEATURE_FLOAT #if !defined(DECIMAL_DIG) #define DECIMAL_DIG DBL_DIG #endif /* Long double sizes */ #ifdef LDBL_DIG #define MAX_MANTISSA_DIGITS LDBL_DIG #define MAX_EXPONENT_DIGITS 4 #define MAX_DOUBLE_DIGITS LDBL_MAX_10_EXP #else #define MAX_MANTISSA_DIGITS DECIMAL_DIG #define MAX_EXPONENT_DIGITS 3 #define MAX_DOUBLE_DIGITS DBL_MAX_10_EXP #endif #if defined(TRIO_COMPILER_ANCIENT) || !defined(LDBL_DIG) #undef LDBL_DIG #undef LDBL_MANT_DIG #undef LDBL_EPSILON #define LDBL_DIG DBL_DIG #define LDBL_MANT_DIG DBL_MANT_DIG #define LDBL_EPSILON DBL_EPSILON #endif #endif /* TRIO_FEATURE_FLOAT */ /* The maximal number of digits is for base 2 */ #define MAX_CHARS_IN(x) (sizeof(x) * CHAR_BIT) /* The width of a pointer. The number of bits in a hex digit is 4 */ #define POINTER_WIDTH ((sizeof("0x") - 1) + sizeof(trio_pointer_t) * CHAR_BIT / 4) #if TRIO_FEATURE_FLOAT /* Infinite and Not-A-Number for floating-point */ #define INFINITE_LOWER "inf" #define INFINITE_UPPER "INF" #define LONG_INFINITE_LOWER "infinite" #define LONG_INFINITE_UPPER "INFINITE" #define NAN_LOWER "nan" #define NAN_UPPER "NAN" #endif /* Various constants */ enum { TYPE_PRINT = 1, #if TRIO_FEATURE_SCANF TYPE_SCAN = 2, #endif /* Flags. FLAGS_LAST must be less than ULONG_MAX */ FLAGS_NEW = 0, FLAGS_STICKY = 1, FLAGS_SPACE = 2 * FLAGS_STICKY, FLAGS_SHOWSIGN = 2 * FLAGS_SPACE, FLAGS_LEFTADJUST = 2 * FLAGS_SHOWSIGN, FLAGS_ALTERNATIVE = 2 * FLAGS_LEFTADJUST, FLAGS_SHORT = 2 * FLAGS_ALTERNATIVE, FLAGS_SHORTSHORT = 2 * FLAGS_SHORT, FLAGS_LONG = 2 * FLAGS_SHORTSHORT, FLAGS_QUAD = 2 * FLAGS_LONG, FLAGS_LONGDOUBLE = 2 * FLAGS_QUAD, FLAGS_SIZE_T = 2 * FLAGS_LONGDOUBLE, FLAGS_PTRDIFF_T = 2 * FLAGS_SIZE_T, FLAGS_INTMAX_T = 2 * FLAGS_PTRDIFF_T, FLAGS_NILPADDING = 2 * FLAGS_INTMAX_T, FLAGS_UNSIGNED = 2 * FLAGS_NILPADDING, FLAGS_UPPER = 2 * FLAGS_UNSIGNED, FLAGS_WIDTH = 2 * FLAGS_UPPER, FLAGS_WIDTH_PARAMETER = 2 * FLAGS_WIDTH, FLAGS_PRECISION = 2 * FLAGS_WIDTH_PARAMETER, FLAGS_PRECISION_PARAMETER = 2 * FLAGS_PRECISION, FLAGS_BASE = 2 * FLAGS_PRECISION_PARAMETER, FLAGS_BASE_PARAMETER = 2 * FLAGS_BASE, FLAGS_FLOAT_E = 2 * FLAGS_BASE_PARAMETER, FLAGS_FLOAT_G = 2 * FLAGS_FLOAT_E, FLAGS_QUOTE = 2 * FLAGS_FLOAT_G, FLAGS_WIDECHAR = 2 * FLAGS_QUOTE, FLAGS_IGNORE = 2 * FLAGS_WIDECHAR, FLAGS_IGNORE_PARAMETER = 2 * FLAGS_IGNORE, FLAGS_VARSIZE_PARAMETER = 2 * FLAGS_IGNORE_PARAMETER, FLAGS_FIXED_SIZE = 2 * FLAGS_VARSIZE_PARAMETER, FLAGS_LAST = FLAGS_FIXED_SIZE, /* Reused flags */ FLAGS_EXCLUDE = FLAGS_SHORT, FLAGS_USER_DEFINED = FLAGS_IGNORE, FLAGS_USER_DEFINED_PARAMETER = FLAGS_IGNORE_PARAMETER, FLAGS_ROUNDING = FLAGS_INTMAX_T, /* Compounded flags */ FLAGS_ALL_VARSIZES = FLAGS_LONG | FLAGS_QUAD | FLAGS_INTMAX_T | FLAGS_PTRDIFF_T | FLAGS_SIZE_T, FLAGS_ALL_SIZES = FLAGS_ALL_VARSIZES | FLAGS_SHORTSHORT | FLAGS_SHORT, NO_POSITION = -1, NO_WIDTH = 0, NO_PRECISION = -1, NO_SIZE = -1, /* Do not change these */ NO_BASE = -1, MIN_BASE = 2, MAX_BASE = 36, BASE_BINARY = 2, BASE_OCTAL = 8, BASE_DECIMAL = 10, BASE_HEX = 16, /* Maximal number of allowed parameters */ MAX_PARAMETERS = 64, /* Maximal number of characters in class */ MAX_CHARACTER_CLASS = UCHAR_MAX + 1, #if TRIO_FEATURE_USER_DEFINED /* Maximal string lengths for user-defined specifiers */ MAX_USER_NAME = 64, MAX_USER_DATA = 256, #endif /* Maximal length of locale separator strings */ MAX_LOCALE_SEPARATOR_LENGTH = MB_LEN_MAX, /* Maximal number of integers in grouping */ MAX_LOCALE_GROUPS = 64 }; #define NO_GROUPING ((int)CHAR_MAX) /* Fundamental formatting parameter types */ #define FORMAT_SENTINEL -1 /* marks end of parameters array */ #define FORMAT_UNKNOWN 0 #define FORMAT_INT 1 #define FORMAT_DOUBLE 2 #define FORMAT_CHAR 3 #define FORMAT_STRING 4 #define FORMAT_POINTER 5 #define FORMAT_COUNT 6 #define FORMAT_PARAMETER 7 #define FORMAT_GROUP 8 #define FORMAT_ERRNO 9 #define FORMAT_USER_DEFINED 10 /* Character constants */ #define CHAR_IDENTIFIER '%' #define CHAR_ALT_IDENTIFIER '$' #define CHAR_BACKSLASH '\\' #define CHAR_QUOTE '\"' #define CHAR_ADJUST ' ' #if TRIO_EXTENSION /* Character class expressions */ #define CLASS_ALNUM "[:alnum:]" #define CLASS_ALPHA "[:alpha:]" #define CLASS_BLANK "[:blank:]" #define CLASS_CNTRL "[:cntrl:]" #define CLASS_DIGIT "[:digit:]" #define CLASS_GRAPH "[:graph:]" #define CLASS_LOWER "[:lower:]" #define CLASS_PRINT "[:print:]" #define CLASS_PUNCT "[:punct:]" #define CLASS_SPACE "[:space:]" #define CLASS_UPPER "[:upper:]" #define CLASS_XDIGIT "[:xdigit:]" #endif /* * SPECIFIERS: * * * a Hex-float * A Hex-float * c Character * C Widechar character (wint_t) * d Decimal * e Float * E Float * F Float * F Float * g Float * G Float * i Integer * m Error message * n Count * o Octal * p Pointer * s String * S Widechar string (wchar_t *) * u Unsigned * x Hex * X Hex * [] Group * <> User-defined * * Reserved: * * D Binary Coded Decimal %D(length,precision) (OS/390) */ #define SPECIFIER_CHAR 'c' #define SPECIFIER_STRING 's' #define SPECIFIER_DECIMAL 'd' #define SPECIFIER_INTEGER 'i' #define SPECIFIER_UNSIGNED 'u' #define SPECIFIER_OCTAL 'o' #define SPECIFIER_HEX 'x' #define SPECIFIER_HEX_UPPER 'X' #if TRIO_FEATURE_FLOAT #define SPECIFIER_FLOAT_E 'e' #define SPECIFIER_FLOAT_E_UPPER 'E' #define SPECIFIER_FLOAT_F 'f' #define SPECIFIER_FLOAT_F_UPPER 'F' #define SPECIFIER_FLOAT_G 'g' #define SPECIFIER_FLOAT_G_UPPER 'G' #endif #define SPECIFIER_POINTER 'p' #if TRIO_FEATURE_SCANF #define SPECIFIER_GROUP '[' #define SPECIFIER_UNGROUP ']' #endif #define SPECIFIER_COUNT 'n' #if TRIO_UNIX98 #define SPECIFIER_CHAR_UPPER 'C' #define SPECIFIER_STRING_UPPER 'S' #endif #define SPECIFIER_HEXFLOAT 'a' #define SPECIFIER_HEXFLOAT_UPPER 'A' #define SPECIFIER_ERRNO 'm' #if TRIO_FEATURE_BINARY #define SPECIFIER_BINARY 'b' #define SPECIFIER_BINARY_UPPER 'B' #endif #if TRIO_FEATURE_USER_DEFINED #define SPECIFIER_USER_DEFINED_BEGIN '<' #define SPECIFIER_USER_DEFINED_END '>' #define SPECIFIER_USER_DEFINED_SEPARATOR ':' #define SPECIFIER_USER_DEFINED_EXTRA '|' #endif /* * QUALIFIERS: * * * Numbers = d,i,o,u,x,X * Float = a,A,e,E,f,F,g,G * String = s * Char = c * * * 9$ Position * Use the 9th parameter. 9 can be any number between 1 and * the maximal argument * * 9 Width * Set width to 9. 9 can be any number, but must not be postfixed * by '$' * * h Short * Numbers: * (unsigned) short int * * hh Short short * Numbers: * (unsigned) char * * l Long * Numbers: * (unsigned) long int * String: * as the S specifier * Char: * as the C specifier * * ll Long Long * Numbers: * (unsigned) long long int * * L Long Double * Float * long double * * # Alternative * Float: * Decimal-point is always present * String: * non-printable characters are handled as \number * * Spacing * * + Sign * * - Alignment * * . Precision * * * Parameter * print: use parameter * scan: no parameter (ignore) * * q Quad * * Z size_t * * w Widechar * * ' Thousands/quote * Numbers: * Integer part grouped in thousands * Binary numbers: * Number grouped in nibbles (4 bits) * String: * Quoted string * * j intmax_t * t prtdiff_t * z size_t * * ! Sticky * @ Parameter (for both print and scan) * * I n-bit Integer * Numbers: * The following options exists * I8 = 8-bit integer * I16 = 16-bit integer * I32 = 32-bit integer * I64 = 64-bit integer */ #define QUALIFIER_POSITION '$' #define QUALIFIER_SHORT 'h' #define QUALIFIER_LONG 'l' #define QUALIFIER_LONG_UPPER 'L' #define QUALIFIER_ALTERNATIVE '#' #define QUALIFIER_SPACE ' ' #define QUALIFIER_PLUS '+' #define QUALIFIER_MINUS '-' #define QUALIFIER_DOT '.' #define QUALIFIER_STAR '*' #define QUALIFIER_CIRCUMFLEX '^' /* For scanlists */ #define QUALIFIER_SIZE_T 'z' #define QUALIFIER_PTRDIFF_T 't' #define QUALIFIER_INTMAX_T 'j' #define QUALIFIER_QUAD 'q' #define QUALIFIER_SIZE_T_UPPER 'Z' #if TRIO_MISC #define QUALIFIER_WIDECHAR 'w' #endif #define QUALIFIER_FIXED_SIZE 'I' #define QUALIFIER_QUOTE '\'' #define QUALIFIER_STICKY '!' #define QUALIFIER_VARSIZE '&' /* This should remain undocumented */ #define QUALIFIER_ROUNDING_UPPER 'R' #if TRIO_EXTENSION #define QUALIFIER_PARAM '@' /* Experimental */ #define QUALIFIER_COLON ':' /* For scanlists */ #define QUALIFIER_EQUAL '=' /* For scanlists */ #endif /************************************************************************* * * Internal Structures * *************************************************************************/ /* Parameters */ typedef struct { /* An indication of which entry in the data union is used */ int type; /* The flags */ trio_flags_t flags; /* The width qualifier */ int width; /* The precision qualifier */ int precision; /* The base qualifier */ int base; /* Base from specifier */ int baseSpecifier; /* The size for the variable size qualifier */ int varsize; /* Offset of the first character of the specifier */ int beginOffset; /* Offset of the first character after the specifier */ int endOffset; /* Position in the argument list that this parameter refers to */ int position; /* The data from the argument list */ union { char* string; #if TRIO_FEATURE_WIDECHAR trio_wchar_t* wstring; #endif trio_pointer_t pointer; union { trio_intmax_t as_signed; trio_uintmax_t as_unsigned; } number; #if TRIO_FEATURE_FLOAT double doubleNumber; double* doublePointer; trio_long_double_t longdoubleNumber; trio_long_double_t* longdoublePointer; #endif int errorNumber; } data; #if TRIO_FEATURE_USER_DEFINED /* For the user-defined specifier */ union { char namespace[MAX_USER_NAME]; int handler; /* if flags & FLAGS_USER_DEFINED_PARAMETER */ } user_defined; char user_data[MAX_USER_DATA]; #endif } trio_parameter_t; /* Container for customized functions */ typedef struct { union { trio_outstream_t out; trio_instream_t in; } stream; trio_pointer_t closure; } trio_custom_t; /* General trio "class" */ typedef struct _trio_class_t { /* * The function to write characters to a stream. */ void(*OutStream) TRIO_PROTO((struct _trio_class_t*, int)); /* * The function to read characters from a stream. */ void(*InStream) TRIO_PROTO((struct _trio_class_t*, int*)); /* * The function to undo read characters from a stream. */ void(*UndoStream) TRIO_PROTO((struct _trio_class_t*)); /* * The current location in the stream. */ trio_pointer_t location; /* * The character currently being processed. */ int current; /* * The number of characters that would have been written/read * if there had been sufficient space. */ int processed; union { /* * The number of characters that are actually written. Processed and * committed will only differ for the *nprintf functions. */ int committed; /* * The number of look-ahead characters read. */ int cached; } actually; /* * The upper limit of characters that may be written/read. */ int max; /* * The last output error that was detected. */ int error; } trio_class_t; /* References (for user-defined callbacks) */ typedef struct _trio_reference_t { trio_class_t* data; trio_parameter_t* parameter; } trio_reference_t; #if TRIO_FEATURE_USER_DEFINED /* Registered entries (for user-defined callbacks) */ typedef struct _trio_userdef_t { struct _trio_userdef_t* next; trio_callback_t callback; char* name; } trio_userdef_t; #endif /************************************************************************* * * Internal Variables * *************************************************************************/ /* Unused but kept for reference */ /* static TRIO_CONST char rcsid[] = "@(#)$Id: trio.c,v 1.131 2010/09/12 11:08:08 breese Exp $"; */ #if TRIO_FEATURE_FLOAT /* * Need this to workaround a parser bug in HP C/iX compiler that fails * to resolves macro definitions that includes type 'long double', * e.g: va_arg(arg_ptr, long double) */ #if defined(TRIO_PLATFORM_MPEIX) static TRIO_CONST trio_long_double_t ___dummy_long_double = 0; #endif #endif static TRIO_CONST char internalNullString[] = "(nil)"; #if defined(USE_LOCALE) static struct lconv* internalLocaleValues = NULL; #endif /* * UNIX98 says "in a locale where the radix character is not defined, * the radix character defaults to a period (.)" */ #if TRIO_FEATURE_FLOAT || TRIO_FEATURE_LOCALE || defined(USE_LOCALE) static int internalDecimalPointLength = 1; static char internalDecimalPoint = '.'; static char internalDecimalPointString[MAX_LOCALE_SEPARATOR_LENGTH + 1] = "."; #endif #if TRIO_FEATURE_QUOTE || TRIO_FEATURE_LOCALE || TRIO_EXTENSION static int internalThousandSeparatorLength = 1; static char internalThousandSeparator[MAX_LOCALE_SEPARATOR_LENGTH + 1] = ","; static char internalGrouping[MAX_LOCALE_GROUPS] = { (char)NO_GROUPING }; #endif static TRIO_CONST char internalDigitsLower[] = "0123456789abcdefghijklmnopqrstuvwxyz"; static TRIO_CONST char internalDigitsUpper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; #if TRIO_FEATURE_SCANF static BOOLEAN_T internalDigitsUnconverted = TRUE; static int internalDigitArray[128]; #if TRIO_EXTENSION static BOOLEAN_T internalCollationUnconverted = TRUE; static char internalCollationArray[MAX_CHARACTER_CLASS][MAX_CHARACTER_CLASS]; #endif #endif #if TRIO_FEATURE_USER_DEFINED static TRIO_VOLATILE trio_callback_t internalEnterCriticalRegion = NULL; static TRIO_VOLATILE trio_callback_t internalLeaveCriticalRegion = NULL; static trio_userdef_t* internalUserDef = NULL; #endif /************************************************************************* * * Internal Functions * ************************************************************************/ #if defined(TRIO_EMBED_NAN) #include "trionan.c" #endif #if defined(TRIO_EMBED_STRING) #include "triostr.c" #endif /************************************************************************* * TrioInitializeParameter * * Description: * Initialize a trio_parameter_t struct. */ TRIO_PRIVATE void TrioInitializeParameter TRIO_ARGS1((parameter), trio_parameter_t* parameter) { parameter->type = FORMAT_UNKNOWN; parameter->flags = 0; parameter->width = 0; parameter->precision = 0; parameter->base = 0; parameter->baseSpecifier = 0; parameter->varsize = 0; parameter->beginOffset = 0; parameter->endOffset = 0; parameter->position = 0; parameter->data.pointer = 0; #if TRIO_FEATURE_USER_DEFINED parameter->user_defined.handler = 0; parameter->user_data[0] = 0; #endif } /************************************************************************* * TrioCopyParameter * * Description: * Copies one trio_parameter_t struct to another. */ TRIO_PRIVATE void TrioCopyParameter TRIO_ARGS2((target, source), trio_parameter_t* target, TRIO_CONST trio_parameter_t* source) { #if TRIO_FEATURE_USER_DEFINED size_t i; #endif target->type = source->type; target->flags = source->flags; target->width = source->width; target->precision = source->precision; target->base = source->base; target->baseSpecifier = source->baseSpecifier; target->varsize = source->varsize; target->beginOffset = source->beginOffset; target->endOffset = source->endOffset; target->position = source->position; target->data = source->data; #if TRIO_FEATURE_USER_DEFINED target->user_defined = source->user_defined; for (i = 0U; i < sizeof(target->user_data); ++i) { if ((target->user_data[i] = source->user_data[i]) == NIL) break; } #endif } /************************************************************************* * TrioIsQualifier * * Description: * Remember to add all new qualifiers to this function. * QUALIFIER_POSITION must not be added. */ TRIO_PRIVATE BOOLEAN_T TrioIsQualifier TRIO_ARGS1((character), TRIO_CONST char character) { /* QUALIFIER_POSITION is not included */ switch (character) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case QUALIFIER_PLUS: case QUALIFIER_MINUS: case QUALIFIER_SPACE: case QUALIFIER_DOT: case QUALIFIER_STAR: case QUALIFIER_ALTERNATIVE: case QUALIFIER_SHORT: case QUALIFIER_LONG: case QUALIFIER_CIRCUMFLEX: case QUALIFIER_LONG_UPPER: case QUALIFIER_SIZE_T: case QUALIFIER_PTRDIFF_T: case QUALIFIER_INTMAX_T: case QUALIFIER_QUAD: case QUALIFIER_SIZE_T_UPPER: #if defined(QUALIFIER_WIDECHAR) case QUALIFIER_WIDECHAR: #endif case QUALIFIER_QUOTE: case QUALIFIER_STICKY: case QUALIFIER_VARSIZE: #if defined(QUALIFIER_PARAM) case QUALIFIER_PARAM: #endif case QUALIFIER_FIXED_SIZE: case QUALIFIER_ROUNDING_UPPER: return TRUE; default: return FALSE; } } /************************************************************************* * TrioSetLocale */ #if defined(USE_LOCALE) TRIO_PRIVATE void TrioSetLocale(TRIO_NOARGS) { internalLocaleValues = (struct lconv*)localeconv(); if (internalLocaleValues) { if ((internalLocaleValues->decimal_point) && (internalLocaleValues->decimal_point[0] != NIL)) { internalDecimalPointLength = trio_length(internalLocaleValues->decimal_point); if (internalDecimalPointLength == 1) { internalDecimalPoint = internalLocaleValues->decimal_point[0]; } else { internalDecimalPoint = NIL; trio_copy_max(internalDecimalPointString, sizeof(internalDecimalPointString), internalLocaleValues->decimal_point); } } #if TRIO_EXTENSION if ((internalLocaleValues->thousands_sep) && (internalLocaleValues->thousands_sep[0] != NIL)) { trio_copy_max(internalThousandSeparator, sizeof(internalThousandSeparator), internalLocaleValues->thousands_sep); internalThousandSeparatorLength = trio_length(internalThousandSeparator); } #endif #if TRIO_EXTENSION if ((internalLocaleValues->grouping) && (internalLocaleValues->grouping[0] != NIL)) { trio_copy_max(internalGrouping, sizeof(internalGrouping), internalLocaleValues->grouping); } #endif } } #endif /* defined(USE_LOCALE) */ #if TRIO_FEATURE_FLOAT && TRIO_FEATURE_QUOTE TRIO_PRIVATE int TrioCalcThousandSeparatorLength TRIO_ARGS1((digits), int digits) { int count = 0; int step = NO_GROUPING; char* groupingPointer = internalGrouping; while (digits > 0) { if (*groupingPointer == CHAR_MAX) { /* Disable grouping */ break; /* while */ } else if (*groupingPointer == 0) { /* Repeat last group */ if (step == NO_GROUPING) { /* Error in locale */ break; /* while */ } } else { step = *groupingPointer++; } if (digits > step) count += internalThousandSeparatorLength; digits -= step; } return count; } #endif /* TRIO_FEATURE_FLOAT && TRIO_FEATURE_QUOTE */ #if TRIO_FEATURE_QUOTE TRIO_PRIVATE BOOLEAN_T TrioFollowedBySeparator TRIO_ARGS1((position), int position) { int step = 0; char* groupingPointer = internalGrouping; position--; if (position == 0) return FALSE; while (position > 0) { if (*groupingPointer == CHAR_MAX) { /* Disable grouping */ break; /* while */ } else if (*groupingPointer != 0) { step = *groupingPointer++; } if (step == 0) break; position -= step; } return (position == 0); } #endif /* TRIO_FEATURE_QUOTE */ /************************************************************************* * TrioGetPosition * * Get the %n$ position. */ TRIO_PRIVATE int TrioGetPosition TRIO_ARGS2((format, offsetPointer), TRIO_CONST char* format, int* offsetPointer) { #if TRIO_FEATURE_POSITIONAL char* tmpformat; int number = 0; int offset = *offsetPointer; number = (int)trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL); offset = (int)(tmpformat - format); if ((number != 0) && (QUALIFIER_POSITION == format[offset++])) { *offsetPointer = offset; /* * number is decreased by 1, because n$ starts from 1, whereas * the array it is indexing starts from 0. */ return number - 1; } #endif return NO_POSITION; } /************************************************************************* * TrioFindNamespace * * Find registered user-defined specifier. * The prev argument is used for optimization only. */ #if TRIO_FEATURE_USER_DEFINED TRIO_PRIVATE trio_userdef_t* TrioFindNamespace TRIO_ARGS2((name, prev), TRIO_CONST char* name, trio_userdef_t** prev) { trio_userdef_t* def; if (internalEnterCriticalRegion) (void)internalEnterCriticalRegion(NULL); for (def = internalUserDef; def; def = def->next) { /* Case-sensitive string comparison */ if (trio_equal_case(def->name, name)) break; if (prev) *prev = def; } if (internalLeaveCriticalRegion) (void)internalLeaveCriticalRegion(NULL); return def; } #endif /************************************************************************* * TrioPower * * Description: * Calculate pow(base, exponent), where number and exponent are integers. */ #if TRIO_FEATURE_FLOAT TRIO_PRIVATE trio_long_double_t TrioPower TRIO_ARGS2((number, exponent), int number, int exponent) { trio_long_double_t result; if (number == 10) { switch (exponent) { /* Speed up calculation of common cases */ case 0: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E-1); break; case 1: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+0); break; case 2: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+1); break; case 3: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+2); break; case 4: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+3); break; case 5: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+4); break; case 6: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+5); break; case 7: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+6); break; case 8: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+7); break; case 9: result = (trio_long_double_t)number * TRIO_SUFFIX_LONG(1E+8); break; default: result = trio_pow((trio_long_double_t)number, (trio_long_double_t)exponent); break; } } else { return trio_pow((trio_long_double_t)number, (trio_long_double_t)exponent); } return result; } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * TrioLogarithm */ #if TRIO_FEATURE_FLOAT TRIO_PRIVATE trio_long_double_t TrioLogarithm TRIO_ARGS2((number, base), trio_long_double_t number, int base) { trio_long_double_t result; if (number <= 0.0) { /* xlC crashes on log(0) */ result = (number == 0.0) ? trio_ninf() : trio_nan(); } else { if (base == 10) { result = trio_log10(number); } else { result = trio_log10(number) / trio_log10((double)base); } } return result; } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * TrioLogarithmBase */ #if TRIO_FEATURE_FLOAT TRIO_PRIVATE double TrioLogarithmBase TRIO_ARGS1((base), int base) { switch (base) { case BASE_BINARY: return 1.0; case BASE_OCTAL: return 3.0; case BASE_DECIMAL: return 3.321928094887362345; case BASE_HEX: return 4.0; default: return TrioLogarithm((double)base, 2); } } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * TrioParseQualifiers * * Description: * Parse the qualifiers of a potential conversion specifier */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" TRIO_PRIVATE int TrioParseQualifiers TRIO_ARGS4((type, format, offset, parameter), int type, TRIO_CONST char* format, int offset, trio_parameter_t* parameter) { char ch; int dots = 0; /* Count number of dots in modifier part */ char* tmpformat; parameter->beginOffset = offset - 1; parameter->flags = FLAGS_NEW; parameter->position = TrioGetPosition(format, &offset); /* Default values */ parameter->width = NO_WIDTH; parameter->precision = NO_PRECISION; parameter->base = NO_BASE; parameter->varsize = NO_SIZE; while (TrioIsQualifier(format[offset])) { ch = format[offset++]; switch (ch) { case QUALIFIER_SPACE: parameter->flags |= FLAGS_SPACE; break; case QUALIFIER_PLUS: parameter->flags |= FLAGS_SHOWSIGN; break; case QUALIFIER_MINUS: parameter->flags |= FLAGS_LEFTADJUST; parameter->flags &= ~FLAGS_NILPADDING; break; case QUALIFIER_ALTERNATIVE: parameter->flags |= FLAGS_ALTERNATIVE; break; case QUALIFIER_DOT: if (dots == 0) /* Precision */ { dots++; /* Skip if no precision */ if (QUALIFIER_DOT == format[offset]) break; /* After the first dot we have the precision */ parameter->flags |= FLAGS_PRECISION; if ((QUALIFIER_STAR == format[offset]) #if defined(QUALIFIER_PARAM) || (QUALIFIER_PARAM == format[offset]) #endif ) { offset++; parameter->flags |= FLAGS_PRECISION_PARAMETER; parameter->precision = TrioGetPosition(format, &offset); } else { parameter->precision = trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL); offset = (int)(tmpformat - format); } } else if (dots == 1) /* Base */ { dots++; /* After the second dot we have the base */ parameter->flags |= FLAGS_BASE; if ((QUALIFIER_STAR == format[offset]) #if defined(QUALIFIER_PARAM) || (QUALIFIER_PARAM == format[offset]) #endif ) { offset++; parameter->flags |= FLAGS_BASE_PARAMETER; parameter->base = TrioGetPosition(format, &offset); } else { parameter->base = trio_to_long(&format[offset], &tmpformat, BASE_DECIMAL); if (parameter->base > MAX_BASE) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); offset = (int)(tmpformat - format); } } else { return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); } break; /* QUALIFIER_DOT */ #if defined(QUALIFIER_PARAM) case QUALIFIER_PARAM: parameter->type = TYPE_PRINT; /* FALLTHROUGH */ #endif case QUALIFIER_STAR: /* This has different meanings for print and scan */ if (TYPE_PRINT == type) { /* Read with from parameter */ int width = TrioGetPosition(format, &offset); parameter->flags |= (FLAGS_WIDTH | FLAGS_WIDTH_PARAMETER); if (NO_POSITION != width) parameter->width = width; /* else keep parameter->width = NO_WIDTH which != NO_POSITION */ } #if TRIO_FEATURE_SCANF else { /* Scan, but do not store result */ parameter->flags |= FLAGS_IGNORE; } #endif break; /* QUALIFIER_STAR */ case '0': if (!(parameter->flags & FLAGS_LEFTADJUST)) parameter->flags |= FLAGS_NILPADDING; /* FALLTHROUGH */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': parameter->flags |= FLAGS_WIDTH; /* * &format[offset - 1] is used to "rewind" the read * character from format */ parameter->width = trio_to_long(&format[offset - 1], &tmpformat, BASE_DECIMAL); offset = (int)(tmpformat - format); break; case QUALIFIER_SHORT: if (parameter->flags & FLAGS_SHORTSHORT) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); else if (parameter->flags & FLAGS_SHORT) parameter->flags |= FLAGS_SHORTSHORT; else parameter->flags |= FLAGS_SHORT; break; case QUALIFIER_LONG: if (parameter->flags & FLAGS_QUAD) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); else if (parameter->flags & FLAGS_LONG) parameter->flags |= FLAGS_QUAD; else parameter->flags |= FLAGS_LONG; break; #if TRIO_FEATURE_LONGDOUBLE case QUALIFIER_LONG_UPPER: parameter->flags |= FLAGS_LONGDOUBLE; break; #endif #if TRIO_FEATURE_SIZE_T case QUALIFIER_SIZE_T: parameter->flags |= FLAGS_SIZE_T; /* Modify flags for later truncation of number */ if (sizeof(size_t) == sizeof(trio_ulonglong_t)) parameter->flags |= FLAGS_QUAD; else if (sizeof(size_t) == sizeof(long)) parameter->flags |= FLAGS_LONG; break; #endif #if TRIO_FEATURE_PTRDIFF_T case QUALIFIER_PTRDIFF_T: parameter->flags |= FLAGS_PTRDIFF_T; if (sizeof(ptrdiff_t) == sizeof(trio_ulonglong_t)) parameter->flags |= FLAGS_QUAD; else if (sizeof(ptrdiff_t) == sizeof(long)) parameter->flags |= FLAGS_LONG; break; #endif #if TRIO_FEATURE_INTMAX_T case QUALIFIER_INTMAX_T: parameter->flags |= FLAGS_INTMAX_T; if (sizeof(trio_intmax_t) == sizeof(trio_ulonglong_t)) parameter->flags |= FLAGS_QUAD; else if (sizeof(trio_intmax_t) == sizeof(long)) parameter->flags |= FLAGS_LONG; break; #endif #if TRIO_FEATURE_QUAD case QUALIFIER_QUAD: parameter->flags |= FLAGS_QUAD; break; #endif #if TRIO_FEATURE_FIXED_SIZE case QUALIFIER_FIXED_SIZE: if (parameter->flags & FLAGS_FIXED_SIZE) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); if (parameter->flags & (FLAGS_ALL_SIZES | FLAGS_LONGDOUBLE | FLAGS_WIDECHAR | FLAGS_VARSIZE_PARAMETER)) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); if ((format[offset] == '6') && (format[offset + 1] == '4')) { parameter->varsize = sizeof(trio_int64_t); offset += 2; } else if ((format[offset] == '3') && (format[offset + 1] == '2')) { parameter->varsize = sizeof(trio_int32_t); offset += 2; } else if ((format[offset] == '1') && (format[offset + 1] == '6')) { parameter->varsize = sizeof(trio_int16_t); offset += 2; } else if (format[offset] == '8') { parameter->varsize = sizeof(trio_int8_t); offset++; } else return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); parameter->flags |= FLAGS_FIXED_SIZE; break; #endif /* TRIO_FEATURE_FIXED_SIZE */ #if defined(QUALIFIER_WIDECHAR) case QUALIFIER_WIDECHAR: parameter->flags |= FLAGS_WIDECHAR; break; #endif #if TRIO_FEATURE_SIZE_T_UPPER case QUALIFIER_SIZE_T_UPPER: break; #endif #if TRIO_FEATURE_QUOTE case QUALIFIER_QUOTE: parameter->flags |= FLAGS_QUOTE; break; #endif #if TRIO_FEATURE_STICKY case QUALIFIER_STICKY: parameter->flags |= FLAGS_STICKY; break; #endif #if TRIO_FEATURE_VARSIZE case QUALIFIER_VARSIZE: parameter->flags |= FLAGS_VARSIZE_PARAMETER; break; #endif #if TRIO_FEATURE_ROUNDING case QUALIFIER_ROUNDING_UPPER: parameter->flags |= FLAGS_ROUNDING; break; #endif default: /* Bail out completely to make the error more obvious */ return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); } } /* while qualifier */ parameter->endOffset = offset; return 0; } #pragma GCC diagnostic pop /************************************************************************* * TrioParseSpecifier * * Description: * Parse the specifier part of a potential conversion specifier */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" TRIO_PRIVATE int TrioParseSpecifier TRIO_ARGS4((type, format, offset, parameter), int type, TRIO_CONST char* format, int offset, trio_parameter_t* parameter) { parameter->baseSpecifier = NO_BASE; switch (format[offset++]) { #if defined(SPECIFIER_CHAR_UPPER) case SPECIFIER_CHAR_UPPER: parameter->flags |= FLAGS_WIDECHAR; /* FALLTHROUGH */ #endif case SPECIFIER_CHAR: if (parameter->flags & FLAGS_LONG) parameter->flags |= FLAGS_WIDECHAR; else if (parameter->flags & FLAGS_SHORT) parameter->flags &= ~FLAGS_WIDECHAR; parameter->type = FORMAT_CHAR; break; #if defined(SPECIFIER_STRING_UPPER) case SPECIFIER_STRING_UPPER: parameter->flags |= FLAGS_WIDECHAR; /* FALLTHROUGH */ #endif case SPECIFIER_STRING: if (parameter->flags & FLAGS_LONG) parameter->flags |= FLAGS_WIDECHAR; else if (parameter->flags & FLAGS_SHORT) parameter->flags &= ~FLAGS_WIDECHAR; parameter->type = FORMAT_STRING; break; #if defined(SPECIFIER_GROUP) case SPECIFIER_GROUP: if (TYPE_SCAN == type) { int depth = 1; parameter->type = FORMAT_GROUP; if (format[offset] == QUALIFIER_CIRCUMFLEX) offset++; if (format[offset] == SPECIFIER_UNGROUP) offset++; if (format[offset] == QUALIFIER_MINUS) offset++; /* Skip nested brackets */ while (format[offset] != NIL) { if (format[offset] == SPECIFIER_GROUP) { depth++; } else if (format[offset] == SPECIFIER_UNGROUP) { if (--depth <= 0) { offset++; break; } } offset++; } } break; #endif /* defined(SPECIFIER_GROUP) */ case SPECIFIER_INTEGER: parameter->type = FORMAT_INT; break; case SPECIFIER_UNSIGNED: parameter->flags |= FLAGS_UNSIGNED; parameter->type = FORMAT_INT; break; case SPECIFIER_DECIMAL: parameter->baseSpecifier = BASE_DECIMAL; parameter->type = FORMAT_INT; break; case SPECIFIER_OCTAL: parameter->flags |= FLAGS_UNSIGNED; parameter->baseSpecifier = BASE_OCTAL; parameter->type = FORMAT_INT; break; #if TRIO_FEATURE_BINARY case SPECIFIER_BINARY_UPPER: parameter->flags |= FLAGS_UPPER; /* FALLTHROUGH */ case SPECIFIER_BINARY: parameter->flags |= FLAGS_NILPADDING; parameter->baseSpecifier = BASE_BINARY; parameter->type = FORMAT_INT; break; #endif case SPECIFIER_HEX_UPPER: parameter->flags |= FLAGS_UPPER; /* FALLTHROUGH */ case SPECIFIER_HEX: parameter->flags |= FLAGS_UNSIGNED; parameter->baseSpecifier = BASE_HEX; parameter->type = FORMAT_INT; break; #if defined(SPECIFIER_FLOAT_E) #if defined(SPECIFIER_FLOAT_E_UPPER) case SPECIFIER_FLOAT_E_UPPER: parameter->flags |= FLAGS_UPPER; /* FALLTHROUGH */ #endif case SPECIFIER_FLOAT_E: parameter->flags |= FLAGS_FLOAT_E; parameter->type = FORMAT_DOUBLE; break; #endif #if defined(SPECIFIER_FLOAT_G) #if defined(SPECIFIER_FLOAT_G_UPPER) case SPECIFIER_FLOAT_G_UPPER: parameter->flags |= FLAGS_UPPER; /* FALLTHROUGH */ #endif case SPECIFIER_FLOAT_G: parameter->flags |= FLAGS_FLOAT_G; parameter->type = FORMAT_DOUBLE; break; #endif #if defined(SPECIFIER_FLOAT_F) #if defined(SPECIFIER_FLOAT_F_UPPER) case SPECIFIER_FLOAT_F_UPPER: parameter->flags |= FLAGS_UPPER; /* FALLTHROUGH */ #endif case SPECIFIER_FLOAT_F: parameter->type = FORMAT_DOUBLE; break; #endif #if defined(TRIO_COMPILER_VISUALC) #pragma warning(push) #pragma warning(disable : 4127) /* Conditional expression is constant */ #endif case SPECIFIER_POINTER: if (sizeof(trio_pointer_t) == sizeof(trio_ulonglong_t)) parameter->flags |= FLAGS_QUAD; else if (sizeof(trio_pointer_t) == sizeof(long)) parameter->flags |= FLAGS_LONG; parameter->type = FORMAT_POINTER; break; #if defined(TRIO_COMPILER_VISUALC) #pragma warning(pop) #endif case SPECIFIER_COUNT: parameter->type = FORMAT_COUNT; break; #if TRIO_FEATURE_HEXFLOAT case SPECIFIER_HEXFLOAT_UPPER: parameter->flags |= FLAGS_UPPER; /* FALLTHROUGH */ case SPECIFIER_HEXFLOAT: parameter->baseSpecifier = BASE_HEX; parameter->type = FORMAT_DOUBLE; break; #endif #if TRIO_FEATURE_ERRNO case SPECIFIER_ERRNO: parameter->type = FORMAT_ERRNO; break; #endif #if TRIO_FEATURE_USER_DEFINED case SPECIFIER_USER_DEFINED_BEGIN: { unsigned int max; int without_namespace = TRUE; char* tmpformat = (char*)&format[offset]; int ch; parameter->type = FORMAT_USER_DEFINED; parameter->user_defined.namespace[0] = NIL; while ((ch = format[offset]) != NIL) { offset++; if ((ch == SPECIFIER_USER_DEFINED_END) || (ch == SPECIFIER_USER_DEFINED_EXTRA)) { if (without_namespace) /* No namespace, handler will be passed as an argument */ parameter->flags |= FLAGS_USER_DEFINED_PARAMETER; /* Copy the user data */ max = (unsigned int)(&format[offset] - tmpformat); if (max > MAX_USER_DATA) max = MAX_USER_DATA; trio_copy_max(parameter->user_data, max, tmpformat); /* Skip extra data (which is only there to keep the compiler happy) */ while ((ch != NIL) && (ch != SPECIFIER_USER_DEFINED_END)) ch = format[offset++]; break; /* while */ } if (ch == SPECIFIER_USER_DEFINED_SEPARATOR) { without_namespace = FALSE; /* Copy the namespace for later looking-up */ max = (int)(&format[offset] - tmpformat); if (max > MAX_USER_NAME) max = MAX_USER_NAME; trio_copy_max(parameter->user_defined.namespace, max, tmpformat); tmpformat = (char*)&format[offset]; } } if (ch != SPECIFIER_USER_DEFINED_END) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); } break; #endif /* TRIO_FEATURE_USER_DEFINED */ default: /* Bail out completely to make the error more obvious */ return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); } parameter->endOffset = offset; return 0; } #pragma GCC diagnostic pop /************************************************************************* * TrioParse * * Description: * Parse the format string */ TRIO_PRIVATE int TrioParse TRIO_ARGS6((type, format, parameters, arglist, argfunc, argarray), int type, TRIO_CONST char* format, trio_parameter_t* parameters, va_list arglist, trio_argfunc_t argfunc, trio_pointer_t* argarray) { /* Count the number of times a parameter is referenced */ unsigned short usedEntries[MAX_PARAMETERS]; /* Parameter counters */ int parameterPosition; int maxParam = -1; /* Utility variables */ int offset; /* Offset into formatting string */ BOOLEAN_T positional; /* Does the specifier have a positional? */ #if TRIO_FEATURE_STICKY BOOLEAN_T gotSticky = FALSE; /* Are there any sticky modifiers at all? */ #endif /* * indices specifies the order in which the parameters must be * read from the va_args (this is necessary to handle positionals) */ int indices[MAX_PARAMETERS]; int pos = 0; /* Various variables */ #if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE) int charlen; #endif int save_errno; int i = -1; int num; trio_parameter_t workParameter; int status; /* Both must be set or none must be set */ assert(((argfunc == NULL) && (argarray == NULL)) || ((argfunc != NULL) && (argarray != NULL))); /* * The 'parameters' array is not initialized, but we need to * know which entries we have used. */ memset(usedEntries, 0, sizeof(usedEntries)); save_errno = errno; offset = 0; parameterPosition = 0; #if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE) (void)mblen(NULL, 0); #endif while (format[offset]) { TrioInitializeParameter(&workParameter); #if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE) if (!isascii(format[offset])) { /* * Multibyte characters cannot be legal specifiers or * modifiers, so we skip over them. */ charlen = mblen(&format[offset], MB_LEN_MAX); offset += (charlen > 0) ? charlen : 1; continue; /* while */ } #endif /* TRIO_COMPILER_SUPPORTS_MULTIBYTE */ switch (format[offset++]) { case CHAR_IDENTIFIER: { if (CHAR_IDENTIFIER == format[offset]) { /* skip double "%" */ offset++; continue; /* while */ } status = TrioParseQualifiers(type, format, offset, &workParameter); if (status < 0) return status; /* Return qualifier syntax error */ status = TrioParseSpecifier(type, format, workParameter.endOffset, &workParameter); if (status < 0) return status; /* Return specifier syntax error */ } break; #if TRIO_EXTENSION case CHAR_ALT_IDENTIFIER: { status = TrioParseQualifiers(type, format, offset, &workParameter); if (status < 0) continue; /* False alert, not a user defined specifier */ status = TrioParseSpecifier(type, format, workParameter.endOffset, &workParameter); if ((status < 0) || (FORMAT_USER_DEFINED != workParameter.type)) continue; /* False alert, not a user defined specifier */ } break; #endif default: continue; /* while */ } /* now handle the parsed conversion specification */ positional = (NO_POSITION != workParameter.position); /* * Parameters only need the type and value. The value is * read later. */ if (workParameter.flags & FLAGS_WIDTH_PARAMETER) { if (workParameter.width == NO_WIDTH) { workParameter.width = parameterPosition++; } else { if (!positional) workParameter.position = workParameter.width + 1; } usedEntries[workParameter.width] += 1; if (workParameter.width > maxParam) maxParam = workParameter.width; parameters[pos].type = FORMAT_PARAMETER; parameters[pos].flags = 0; indices[workParameter.width] = pos; workParameter.width = pos++; } if (workParameter.flags & FLAGS_PRECISION_PARAMETER) { if (workParameter.precision == NO_PRECISION) { workParameter.precision = parameterPosition++; } else { if (!positional) workParameter.position = workParameter.precision + 1; } usedEntries[workParameter.precision] += 1; if (workParameter.precision > maxParam) maxParam = workParameter.precision; parameters[pos].type = FORMAT_PARAMETER; parameters[pos].flags = 0; indices[workParameter.precision] = pos; workParameter.precision = pos++; } if (workParameter.flags & FLAGS_BASE_PARAMETER) { if (workParameter.base == NO_BASE) { workParameter.base = parameterPosition++; } else { if (!positional) workParameter.position = workParameter.base + 1; } usedEntries[workParameter.base] += 1; if (workParameter.base > maxParam) maxParam = workParameter.base; parameters[pos].type = FORMAT_PARAMETER; parameters[pos].flags = 0; indices[workParameter.base] = pos; workParameter.base = pos++; } #if TRIO_FEATURE_VARSIZE if (workParameter.flags & FLAGS_VARSIZE_PARAMETER) { workParameter.varsize = parameterPosition++; usedEntries[workParameter.varsize] += 1; if (workParameter.varsize > maxParam) maxParam = workParameter.varsize; parameters[pos].type = FORMAT_PARAMETER; parameters[pos].flags = 0; indices[workParameter.varsize] = pos; workParameter.varsize = pos++; } #endif #if TRIO_FEATURE_USER_DEFINED if (workParameter.flags & FLAGS_USER_DEFINED_PARAMETER) { workParameter.user_defined.handler = parameterPosition++; usedEntries[workParameter.user_defined.handler] += 1; if (workParameter.user_defined.handler > maxParam) maxParam = workParameter.user_defined.handler; parameters[pos].type = FORMAT_PARAMETER; parameters[pos].flags = FLAGS_USER_DEFINED; indices[workParameter.user_defined.handler] = pos; workParameter.user_defined.handler = pos++; } #endif if (NO_POSITION == workParameter.position) { workParameter.position = parameterPosition++; } if (workParameter.position > maxParam) maxParam = workParameter.position; if (workParameter.position >= MAX_PARAMETERS) { /* Bail out completely to make the error more obvious */ return TRIO_ERROR_RETURN(TRIO_ETOOMANY, offset); } indices[workParameter.position] = pos; /* Count the number of times this entry has been used */ usedEntries[workParameter.position] += 1; /* Find last sticky parameters */ #if TRIO_FEATURE_STICKY if (workParameter.flags & FLAGS_STICKY) { gotSticky = TRUE; } else if (gotSticky) { for (i = pos - 1; i >= 0; i--) { if (parameters[i].type == FORMAT_PARAMETER) continue; if ((parameters[i].flags & FLAGS_STICKY) && (parameters[i].type == workParameter.type)) { /* Do not overwrite current qualifiers */ workParameter.flags |= (parameters[i].flags & (unsigned long)~FLAGS_STICKY); if (workParameter.width == NO_WIDTH) workParameter.width = parameters[i].width; if (workParameter.precision == NO_PRECISION) workParameter.precision = parameters[i].precision; if (workParameter.base == NO_BASE) workParameter.base = parameters[i].base; break; } } } #endif if (workParameter.base == NO_BASE) workParameter.base = BASE_DECIMAL; offset = workParameter.endOffset; TrioCopyParameter(&parameters[pos++], &workParameter); } /* while format characters left */ parameters[pos].type = FORMAT_SENTINEL; /* end parameter array with sentinel */ parameters[pos].beginOffset = offset; for (num = 0; num <= maxParam; num++) { if (usedEntries[num] != 1) { if (usedEntries[num] == 0) /* gap detected */ return TRIO_ERROR_RETURN(TRIO_EGAP, num); else /* double references detected */ return TRIO_ERROR_RETURN(TRIO_EDBLREF, num); } i = indices[num]; /* * FORMAT_PARAMETERS are only present if they must be read, * so it makes no sense to check the ignore flag (besides, * the flags variable is not set for that particular type) */ if ((parameters[i].type != FORMAT_PARAMETER) && (parameters[i].flags & FLAGS_IGNORE)) continue; /* for all arguments */ /* * The stack arguments are read according to ANSI C89 * default argument promotions: * * char = int * short = int * unsigned char = unsigned int * unsigned short = unsigned int * float = double * * In addition to the ANSI C89 these types are read (the * default argument promotions of C99 has not been * considered yet) * * long long * long double * size_t * ptrdiff_t * intmax_t */ switch (parameters[i].type) { case FORMAT_GROUP: case FORMAT_STRING: #if TRIO_FEATURE_WIDECHAR if (parameters[i].flags & FLAGS_WIDECHAR) { parameters[i].data.wstring = (argfunc == NULL) ? va_arg(arglist, trio_wchar_t*) : (trio_wchar_t*)(argfunc(argarray, num, TRIO_TYPE_PWCHAR)); } else #endif { parameters[i].data.string = (argfunc == NULL) ? va_arg(arglist, char*) : (char*)(argfunc(argarray, num, TRIO_TYPE_PCHAR)); } break; #if TRIO_FEATURE_USER_DEFINED case FORMAT_USER_DEFINED: #endif case FORMAT_POINTER: case FORMAT_COUNT: case FORMAT_UNKNOWN: parameters[i].data.pointer = (argfunc == NULL) ? va_arg(arglist, trio_pointer_t) : argfunc(argarray, num, TRIO_TYPE_POINTER); break; case FORMAT_CHAR: case FORMAT_INT: #if TRIO_FEATURE_SCANF if (TYPE_SCAN == type) { if (argfunc == NULL) parameters[i].data.pointer = (trio_pointer_t)va_arg(arglist, trio_pointer_t); else { if (parameters[i].type == FORMAT_CHAR) parameters[i].data.pointer = (trio_pointer_t)((char*)argfunc(argarray, num, TRIO_TYPE_CHAR)); else if (parameters[i].flags & FLAGS_SHORT) parameters[i].data.pointer = (trio_pointer_t)((short*)argfunc(argarray, num, TRIO_TYPE_SHORT)); else parameters[i].data.pointer = (trio_pointer_t)((int*)argfunc(argarray, num, TRIO_TYPE_INT)); } } else #endif /* TRIO_FEATURE_SCANF */ { #if TRIO_FEATURE_VARSIZE || TRIO_FEATURE_FIXED_SIZE if (parameters[i].flags & (FLAGS_VARSIZE_PARAMETER | FLAGS_FIXED_SIZE)) { int varsize; if (parameters[i].flags & FLAGS_VARSIZE_PARAMETER) { /* * Variable sizes are mapped onto the fixed sizes, in * accordance with integer promotion. * * Please note that this may not be portable, as we * only guess the size, not the layout of the numbers. * For example, if int is little-endian, and long is * big-endian, then this will fail. */ varsize = (int)parameters[parameters[i].varsize].data.number.as_unsigned; } else { /* Used for the I<bits> modifiers */ varsize = parameters[i].varsize; } parameters[i].flags &= ~FLAGS_ALL_VARSIZES; if (varsize <= (int)sizeof(int)) ; else if (varsize <= (int)sizeof(long)) parameters[i].flags |= FLAGS_LONG; #if TRIO_FEATURE_INTMAX_T else if (varsize <= (int)sizeof(trio_longlong_t)) parameters[i].flags |= FLAGS_QUAD; else parameters[i].flags |= FLAGS_INTMAX_T; #else else parameters[i].flags |= FLAGS_QUAD; #endif } #endif /* TRIO_FEATURE_VARSIZE */ #if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER if (parameters[i].flags & FLAGS_SIZE_T) parameters[i].data.number.as_unsigned = (argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, size_t) : (trio_uintmax_t)( *((size_t*)argfunc(argarray, num, TRIO_TYPE_SIZE))); else #endif #if TRIO_FEATURE_PTRDIFF_T if (parameters[i].flags & FLAGS_PTRDIFF_T) parameters[i].data.number.as_unsigned = (argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, ptrdiff_t) : (trio_uintmax_t)( *((ptrdiff_t*)argfunc(argarray, num, TRIO_TYPE_PTRDIFF))); else #endif #if TRIO_FEATURE_INTMAX_T if (parameters[i].flags & FLAGS_INTMAX_T) parameters[i].data.number.as_unsigned = (argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, trio_intmax_t) : (trio_uintmax_t)( *((trio_intmax_t*)argfunc(argarray, num, TRIO_TYPE_UINTMAX))); else #endif if (parameters[i].flags & FLAGS_QUAD) parameters[i].data.number.as_unsigned = (argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, trio_ulonglong_t) : (trio_uintmax_t)(*((trio_ulonglong_t*)argfunc( argarray, num, TRIO_TYPE_ULONGLONG))); else if (parameters[i].flags & FLAGS_LONG) parameters[i].data.number.as_unsigned = (argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, long) : (trio_uintmax_t)(*( (long*)argfunc(argarray, num, TRIO_TYPE_LONG))); else { if (argfunc == NULL) parameters[i].data.number.as_unsigned = (trio_uintmax_t)va_arg(arglist, int); else { if (parameters[i].type == FORMAT_CHAR) parameters[i].data.number.as_unsigned = (trio_uintmax_t)( *((char*)argfunc(argarray, num, TRIO_TYPE_CHAR))); else if (parameters[i].flags & FLAGS_SHORT) parameters[i].data.number.as_unsigned = (trio_uintmax_t)( *((short*)argfunc(argarray, num, TRIO_TYPE_SHORT))); else parameters[i].data.number.as_unsigned = (trio_uintmax_t)( *((int*)argfunc(argarray, num, TRIO_TYPE_INT))); } } } break; case FORMAT_PARAMETER: /* * The parameter for the user-defined specifier is a pointer, * whereas the rest (width, precision, base) uses an integer. */ if (parameters[i].flags & FLAGS_USER_DEFINED) parameters[i].data.pointer = (argfunc == NULL) ? va_arg(arglist, trio_pointer_t) : argfunc(argarray, num, TRIO_TYPE_POINTER); else parameters[i].data.number.as_unsigned = (argfunc == NULL) ? (trio_uintmax_t)va_arg(arglist, int) : (trio_uintmax_t)(*((int*)argfunc(argarray, num, TRIO_TYPE_INT))); break; #if TRIO_FEATURE_FLOAT case FORMAT_DOUBLE: #if TRIO_FEATURE_SCANF if (TYPE_SCAN == type) { if (parameters[i].flags & FLAGS_LONGDOUBLE) parameters[i].data.longdoublePointer = (argfunc == NULL) ? va_arg(arglist, trio_long_double_t*) : (trio_long_double_t*)argfunc(argarray, num, TRIO_TYPE_LONGDOUBLE); else { if (parameters[i].flags & FLAGS_LONG) parameters[i].data.doublePointer = (argfunc == NULL) ? va_arg(arglist, double*) : (double*)argfunc(argarray, num, TRIO_TYPE_DOUBLE); else parameters[i].data.doublePointer = (argfunc == NULL) ? (double*)va_arg(arglist, float*) : (double*)argfunc(argarray, num, TRIO_TYPE_DOUBLE); } } else #endif /* TRIO_FEATURE_SCANF */ { if (parameters[i].flags & FLAGS_LONGDOUBLE) parameters[i].data.longdoubleNumber = (argfunc == NULL) ? va_arg(arglist, trio_long_double_t) : (trio_long_double_t)(*((trio_long_double_t*)argfunc( argarray, num, TRIO_TYPE_LONGDOUBLE))); else { if (argfunc == NULL) parameters[i].data.longdoubleNumber = (trio_long_double_t)va_arg(arglist, double); else { if (parameters[i].flags & FLAGS_SHORT) parameters[i].data.longdoubleNumber = (trio_long_double_t)( *((float*)argfunc(argarray, num, TRIO_TYPE_FLOAT))); else parameters[i].data.longdoubleNumber = (trio_long_double_t)( *((double*)argfunc(argarray, num, TRIO_TYPE_DOUBLE))); } } } break; #endif /* TRIO_FEATURE_FLOAT */ #if TRIO_FEATURE_ERRNO case FORMAT_ERRNO: parameters[i].data.errorNumber = save_errno; break; #endif default: break; } } /* for all specifiers */ return num; } /************************************************************************* * * FORMATTING * ************************************************************************/ /************************************************************************* * TrioWriteNumber * * Description: * Output a number. * The complexity of this function is a result of the complexity * of the dependencies of the flags. */ TRIO_PRIVATE void TrioWriteNumber TRIO_ARGS6((self, number, flags, width, precision, base), trio_class_t* self, trio_uintmax_t number, trio_flags_t flags, int width, int precision, int base) { BOOLEAN_T isNegative; BOOLEAN_T isNumberZero; BOOLEAN_T isPrecisionZero; BOOLEAN_T ignoreNumber; char buffer[MAX_CHARS_IN(trio_uintmax_t) * (1 + MAX_LOCALE_SEPARATOR_LENGTH) + 1]; char* bufferend; char* pointer; TRIO_CONST char* digits; int i; #if TRIO_FEATURE_QUOTE int length; char* p; #endif int count; int digitOffset; assert(VALID(self)); assert(VALID(self->OutStream)); assert(((base >= MIN_BASE) && (base <= MAX_BASE)) || (base == NO_BASE)); digits = (flags & FLAGS_UPPER) ? internalDigitsUpper : internalDigitsLower; if (base == NO_BASE) base = BASE_DECIMAL; isNumberZero = (number == 0); isPrecisionZero = (precision == 0); ignoreNumber = (isNumberZero && isPrecisionZero && !((flags & FLAGS_ALTERNATIVE) && (base == BASE_OCTAL))); if (flags & FLAGS_UNSIGNED) { isNegative = FALSE; flags &= ~FLAGS_SHOWSIGN; } else { isNegative = ((trio_intmax_t)number < 0); if (isNegative) number = -((trio_intmax_t)number); } if (flags & FLAGS_QUAD) number &= (trio_ulonglong_t)-1; else if (flags & FLAGS_LONG) number &= (unsigned long)-1; else number &= (unsigned int)-1; /* Build number */ pointer = bufferend = &buffer[sizeof(buffer) - 1]; *pointer-- = NIL; for (i = 1; i < (int)sizeof(buffer); i++) { digitOffset = number % base; *pointer-- = digits[digitOffset]; number /= base; if (number == 0) break; #if TRIO_FEATURE_QUOTE if ((flags & FLAGS_QUOTE) && TrioFollowedBySeparator(i + 1)) { /* * We are building the number from the least significant * to the most significant digit, so we have to copy the * thousand separator backwards */ length = internalThousandSeparatorLength; if (((int)(pointer - buffer) - length) > 0) { p = &internalThousandSeparator[length - 1]; while (length-- > 0) *pointer-- = *p--; } } #endif } if (!ignoreNumber) { /* Adjust width */ width -= (bufferend - pointer) - 1; } /* Adjust precision */ if (NO_PRECISION != precision) { precision -= (bufferend - pointer) - 1; if (precision < 0) precision = 0; flags |= FLAGS_NILPADDING; } /* Calculate padding */ count = (!((flags & FLAGS_LEFTADJUST) || (precision == NO_PRECISION))) ? precision : 0; /* Adjust width further */ if (isNegative || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE)) width--; if ((flags & FLAGS_ALTERNATIVE) && !isNumberZero) { switch (base) { case BASE_BINARY: case BASE_HEX: width -= 2; break; case BASE_OCTAL: if (!(flags & FLAGS_NILPADDING) || (count == 0)) width--; break; default: break; } } /* Output prefixes spaces if needed */ if (!((flags & FLAGS_LEFTADJUST) || ((flags & FLAGS_NILPADDING) && (precision == NO_PRECISION)))) { while (width-- > count) self->OutStream(self, CHAR_ADJUST); } /* width has been adjusted for signs and alternatives */ if (isNegative) self->OutStream(self, '-'); else if (flags & FLAGS_SHOWSIGN) self->OutStream(self, '+'); else if (flags & FLAGS_SPACE) self->OutStream(self, ' '); /* Prefix is not written when the value is zero */ if ((flags & FLAGS_ALTERNATIVE) && !isNumberZero) { switch (base) { case BASE_BINARY: self->OutStream(self, '0'); self->OutStream(self, (flags & FLAGS_UPPER) ? 'B' : 'b'); break; case BASE_OCTAL: if (!(flags & FLAGS_NILPADDING) || (count == 0)) self->OutStream(self, '0'); break; case BASE_HEX: self->OutStream(self, '0'); self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x'); break; default: break; } /* switch base */ } /* Output prefixed zero padding if needed */ if (flags & FLAGS_NILPADDING) { if (precision == NO_PRECISION) precision = width; while (precision-- > 0) { self->OutStream(self, '0'); width--; } } if (!ignoreNumber) { /* Output the number itself */ while (*(++pointer)) { self->OutStream(self, *pointer); } } /* Output trailing spaces if needed */ if (flags & FLAGS_LEFTADJUST) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } } /************************************************************************* * TrioWriteStringCharacter * * Description: * Output a single character of a string */ TRIO_PRIVATE void TrioWriteStringCharacter TRIO_ARGS3((self, ch, flags), trio_class_t* self, int ch, trio_flags_t flags) { if (flags & FLAGS_ALTERNATIVE) { if (!isprint(ch)) { /* * Non-printable characters are converted to C escapes or * \number, if no C escape exists. */ self->OutStream(self, CHAR_BACKSLASH); switch (ch) { case '\007': self->OutStream(self, 'a'); break; case '\b': self->OutStream(self, 'b'); break; case '\f': self->OutStream(self, 'f'); break; case '\n': self->OutStream(self, 'n'); break; case '\r': self->OutStream(self, 'r'); break; case '\t': self->OutStream(self, 't'); break; case '\v': self->OutStream(self, 'v'); break; case '\\': self->OutStream(self, '\\'); break; default: self->OutStream(self, 'x'); TrioWriteNumber(self, (trio_uintmax_t)ch, FLAGS_UNSIGNED | FLAGS_NILPADDING, 2, 2, BASE_HEX); break; } } else if (ch == CHAR_BACKSLASH) { self->OutStream(self, CHAR_BACKSLASH); self->OutStream(self, CHAR_BACKSLASH); } else { self->OutStream(self, ch); } } else { self->OutStream(self, ch); } } /************************************************************************* * TrioWriteString * * Description: * Output a string */ TRIO_PRIVATE void TrioWriteString TRIO_ARGS5((self, string, flags, width, precision), trio_class_t* self, TRIO_CONST char* string, trio_flags_t flags, int width, int precision) { int length = 0; int ch; assert(VALID(self)); assert(VALID(self->OutStream)); if (string == NULL) { string = internalNullString; length = sizeof(internalNullString) - 1; #if TRIO_FEATURE_QUOTE /* Disable quoting for the null pointer */ flags &= (~FLAGS_QUOTE); #endif width = 0; } else { if (precision <= 0) { length = trio_length(string); } else { length = trio_length_max(string, precision); } } if ((NO_PRECISION != precision) && (precision < length)) { length = precision; } width -= length; #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) self->OutStream(self, CHAR_QUOTE); #endif if (!(flags & FLAGS_LEFTADJUST)) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } while (length-- > 0) { /* The ctype parameters must be an unsigned char (or EOF) */ ch = (int)((unsigned char)(*string++)); TrioWriteStringCharacter(self, ch, flags); } if (flags & FLAGS_LEFTADJUST) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) self->OutStream(self, CHAR_QUOTE); #endif } /************************************************************************* * TrioWriteWideStringCharacter * * Description: * Output a wide string as a multi-byte sequence */ #if TRIO_FEATURE_WIDECHAR TRIO_PRIVATE int TrioWriteWideStringCharacter TRIO_ARGS4((self, wch, flags, width), trio_class_t* self, trio_wchar_t wch, trio_flags_t flags, int width) { int size; int i; int ch; char* string; char buffer[MB_LEN_MAX + 1]; if (width == NO_WIDTH) width = sizeof(buffer); size = wctomb(buffer, wch); if ((size <= 0) || (size > width) || (buffer[0] == NIL)) return 0; string = buffer; i = size; while ((width >= i) && (width-- > 0) && (i-- > 0)) { /* The ctype parameters must be an unsigned char (or EOF) */ ch = (int)((unsigned char)(*string++)); TrioWriteStringCharacter(self, ch, flags); } return size; } #endif /* TRIO_FEATURE_WIDECHAR */ /************************************************************************* * TrioWriteWideString * * Description: * Output a wide character string as a multi-byte string */ #if TRIO_FEATURE_WIDECHAR TRIO_PRIVATE void TrioWriteWideString TRIO_ARGS5((self, wstring, flags, width, precision), trio_class_t* self, TRIO_CONST trio_wchar_t* wstring, trio_flags_t flags, int width, int precision) { int length; int size; assert(VALID(self)); assert(VALID(self->OutStream)); #if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE) /* Required by TrioWriteWideStringCharacter */ (void)mblen(NULL, 0); #endif if (wstring == NULL) { TrioWriteString(self, NULL, flags, width, precision); return; } if (NO_PRECISION == precision) { length = INT_MAX; } else { length = precision; width -= length; } #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) self->OutStream(self, CHAR_QUOTE); #endif if (!(flags & FLAGS_LEFTADJUST)) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } while (length > 0) { size = TrioWriteWideStringCharacter(self, *wstring++, flags, length); if (size == 0) break; /* while */ length -= size; } if (flags & FLAGS_LEFTADJUST) { while (width-- > 0) self->OutStream(self, CHAR_ADJUST); } #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) self->OutStream(self, CHAR_QUOTE); #endif } #endif /* TRIO_FEATURE_WIDECHAR */ /************************************************************************* * TrioWriteDouble * * http://wwwold.dkuug.dk/JTC1/SC22/WG14/www/docs/dr_211.htm * * "5.2.4.2.2 paragraph #4 * * The accuracy [...] is implementation defined, as is the accuracy * of the conversion between floating-point internal representations * and string representations performed by the libray routine in * <stdio.h>" */ /* FIXME: handle all instances of constant long-double number (L) * and *l() math functions. */ #if TRIO_FEATURE_FLOAT TRIO_PRIVATE void TrioWriteDouble TRIO_ARGS6((self, number, flags, width, precision, base), trio_class_t* self, trio_long_double_t number, trio_flags_t flags, int width, int precision, int base) { trio_long_double_t integerNumber; trio_long_double_t fractionNumber; trio_long_double_t workNumber; int integerDigits; int fractionDigits; int exponentDigits; int workDigits; int baseDigits; int integerThreshold; int fractionThreshold; int expectedWidth; int exponent = 0; unsigned int uExponent = 0; int exponentBase; trio_long_double_t dblBase; trio_long_double_t dblFractionBase; trio_long_double_t integerAdjust; trio_long_double_t fractionAdjust; trio_long_double_t workFractionNumber; trio_long_double_t workFractionAdjust; int fractionDigitsInspect; BOOLEAN_T isNegative; BOOLEAN_T isExponentNegative = FALSE; BOOLEAN_T requireTwoDigitExponent; BOOLEAN_T isHex; TRIO_CONST char* digits; #if TRIO_FEATURE_QUOTE char* groupingPointer; #endif int i; int offset; BOOLEAN_T hasOnlyZeroes; int leadingFractionZeroes = -1; register int trailingZeroes; BOOLEAN_T keepTrailingZeroes; BOOLEAN_T keepDecimalPoint; trio_long_double_t epsilon; BOOLEAN_T adjustNumber = FALSE; assert(VALID(self)); assert(VALID(self->OutStream)); assert(((base >= MIN_BASE) && (base <= MAX_BASE)) || (base == NO_BASE)); /* Determine sign and look for special quantities */ switch (trio_fpclassify_and_signbit(number, &isNegative)) { case TRIO_FP_NAN: TrioWriteString(self, (flags & FLAGS_UPPER) ? NAN_UPPER : NAN_LOWER, flags, width, precision); return; case TRIO_FP_INFINITE: if (isNegative) { /* Negative infinity */ TrioWriteString(self, (flags & FLAGS_UPPER) ? "-" INFINITE_UPPER : "-" INFINITE_LOWER, flags, width, precision); return; } else { /* Positive infinity */ TrioWriteString(self, (flags & FLAGS_UPPER) ? INFINITE_UPPER : INFINITE_LOWER, flags, width, precision); return; } default: /* Finitude */ break; } /* Normal numbers */ if (flags & FLAGS_LONGDOUBLE) { baseDigits = (base == 10) ? LDBL_DIG : (int)trio_floor(LDBL_MANT_DIG / TrioLogarithmBase(base)); epsilon = LDBL_EPSILON; } else if (flags & FLAGS_SHORT) { baseDigits = (base == BASE_DECIMAL) ? FLT_DIG : (int)trio_floor(FLT_MANT_DIG / TrioLogarithmBase(base)); epsilon = FLT_EPSILON; } else { baseDigits = (base == BASE_DECIMAL) ? DBL_DIG : (int)trio_floor(DBL_MANT_DIG / TrioLogarithmBase(base)); epsilon = DBL_EPSILON; } digits = (flags & FLAGS_UPPER) ? internalDigitsUpper : internalDigitsLower; isHex = (base == BASE_HEX); if (base == NO_BASE) base = BASE_DECIMAL; dblBase = (trio_long_double_t)base; keepTrailingZeroes = !((flags & FLAGS_ROUNDING) || ((flags & FLAGS_FLOAT_G) && !(flags & FLAGS_ALTERNATIVE))); #if TRIO_FEATURE_ROUNDING if (flags & FLAGS_ROUNDING) { precision = baseDigits; } #endif if (precision == NO_PRECISION) { if (isHex) { keepTrailingZeroes = FALSE; precision = FLT_MANT_DIG; } else { precision = FLT_DIG; } } if (isNegative) { number = -number; } if (isHex) { flags |= FLAGS_FLOAT_E; } reprocess: if (flags & FLAGS_FLOAT_G) { if (precision == 0) precision = 1; if ((number < TRIO_SUFFIX_LONG(1.0E-4)) || (number >= TrioPower(base, (trio_long_double_t)precision))) { /* Use scientific notation */ flags |= FLAGS_FLOAT_E; } else if (number < 1.0) { /* * Use normal notation. If the integer part of the number is * zero, then adjust the precision to include leading fractional * zeros. */ workNumber = TrioLogarithm(number, base); workNumber = TRIO_FABS(workNumber); if (workNumber - trio_floor(workNumber) < epsilon) workNumber--; leadingFractionZeroes = (int)trio_floor(workNumber); } } if (flags & FLAGS_FLOAT_E) { /* Scale the number */ workNumber = TrioLogarithm(number, base); if (trio_isinf(workNumber) == -1) { exponent = 0; /* Undo setting */ if (flags & FLAGS_FLOAT_G) flags &= ~FLAGS_FLOAT_E; } else { exponent = (int)trio_floor(workNumber); workNumber = number; /* * The expression A * 10^-B is equivalent to A / 10^B but the former * usually gives better accuracy. */ workNumber *= TrioPower(dblBase, (trio_long_double_t)-exponent); if (trio_isinf(workNumber)) { /* * Scaling is done it two steps to avoid problems with subnormal * numbers. */ workNumber /= TrioPower(dblBase, (trio_long_double_t)(exponent / 2)); workNumber /= TrioPower(dblBase, (trio_long_double_t)(exponent - (exponent / 2))); } number = workNumber; isExponentNegative = (exponent < 0); uExponent = (isExponentNegative) ? -exponent : exponent; if (isHex) uExponent *= 4; /* log16(2) */ #if TRIO_FEATURE_QUOTE /* No thousand separators */ flags &= ~FLAGS_QUOTE; #endif } } integerNumber = trio_floor(number); fractionNumber = number - integerNumber; /* * Truncated number. * * Precision is number of significant digits for FLOAT_G and number of * fractional digits for others. */ integerDigits = 1; if (integerNumber > epsilon) { integerDigits += (int)TrioLogarithm(integerNumber, base); } fractionDigits = precision; if (flags & FLAGS_FLOAT_G) { if (leadingFractionZeroes > 0) { fractionDigits += leadingFractionZeroes; } if ((integerNumber > epsilon) || (number <= epsilon)) { fractionDigits -= integerDigits; } } dblFractionBase = TrioPower(base, fractionDigits); if (integerNumber < 1.0) { workNumber = number * dblFractionBase + TRIO_SUFFIX_LONG(0.5); if (trio_floor(number * dblFractionBase) != trio_floor(workNumber)) { adjustNumber = TRUE; /* Remove a leading fraction zero if fraction is rounded up */ if ((int)TrioLogarithm(number * dblFractionBase, base) != (int)TrioLogarithm(workNumber, base)) { --leadingFractionZeroes; } } workNumber /= dblFractionBase; } else { workNumber = number + TRIO_SUFFIX_LONG(0.5) / dblFractionBase; adjustNumber = (trio_floor(number) != trio_floor(workNumber)); } if (adjustNumber) { if ((flags & FLAGS_FLOAT_G) && !(flags & FLAGS_FLOAT_E)) { /* The adjustment may require a change to scientific notation */ if ((workNumber < TRIO_SUFFIX_LONG(1.0E-4)) || (workNumber >= TrioPower(base, (trio_long_double_t)precision))) { /* Use scientific notation */ flags |= FLAGS_FLOAT_E; goto reprocess; } } if (flags & FLAGS_FLOAT_E) { workDigits = 1 + TrioLogarithm(trio_floor(workNumber), base); if (integerDigits == workDigits) { /* Adjust if the same number of digits are used */ number += TRIO_SUFFIX_LONG(0.5) / dblFractionBase; integerNumber = trio_floor(number); fractionNumber = number - integerNumber; } else { /* Adjust if number was rounded up one digit (ie. 0.99 to 1.00) */ exponent++; isExponentNegative = (exponent < 0); uExponent = (isExponentNegative) ? -exponent : exponent; if (isHex) uExponent *= 4; /* log16(2) */ workNumber = (number + TRIO_SUFFIX_LONG(0.5) / dblFractionBase) / dblBase; integerNumber = trio_floor(workNumber); fractionNumber = workNumber - integerNumber; } } else { if (workNumber > 1.0) { /* Adjust if number was rounded up one digit (ie. 99 to 100) */ integerNumber = trio_floor(workNumber); fractionNumber = 0.0; integerDigits = (integerNumber > epsilon) ? 1 + (int)TrioLogarithm(integerNumber, base) : 1; if (flags & FLAGS_FLOAT_G) { if (flags & FLAGS_ALTERNATIVE) { fractionDigits = precision; if ((integerNumber > epsilon) || (number <= epsilon)) { fractionDigits -= integerDigits; } } else { fractionDigits = 0; } } } else { integerNumber = trio_floor(workNumber); fractionNumber = workNumber - integerNumber; if (flags & FLAGS_FLOAT_G) { if (flags & FLAGS_ALTERNATIVE) { fractionDigits = precision; if (leadingFractionZeroes > 0) { fractionDigits += leadingFractionZeroes; } if ((integerNumber > epsilon) || (number <= epsilon)) { fractionDigits -= integerDigits; } } } } } } /* Estimate accuracy */ integerAdjust = fractionAdjust = TRIO_SUFFIX_LONG(0.5); #if TRIO_FEATURE_ROUNDING if (flags & FLAGS_ROUNDING) { if (integerDigits > baseDigits) { integerThreshold = baseDigits; fractionDigits = 0; dblFractionBase = 1.0; fractionThreshold = 0; precision = 0; /* Disable decimal-point */ integerAdjust = TrioPower(base, integerDigits - integerThreshold - 1); fractionAdjust = 0.0; } else { integerThreshold = integerDigits; fractionThreshold = fractionDigits - integerThreshold; fractionAdjust = 1.0; } } else #endif { integerThreshold = INT_MAX; fractionThreshold = INT_MAX; } /* * Calculate expected width. * sign + integer part + thousands separators + decimal point * + fraction + exponent */ fractionAdjust /= dblFractionBase; hasOnlyZeroes = (trio_floor((fractionNumber + fractionAdjust) * dblFractionBase) < epsilon); keepDecimalPoint = ((flags & FLAGS_ALTERNATIVE) || !((precision == 0) || (!keepTrailingZeroes && hasOnlyZeroes))); expectedWidth = integerDigits + fractionDigits; if (!keepTrailingZeroes) { trailingZeroes = 0; workFractionNumber = fractionNumber; workFractionAdjust = fractionAdjust; fractionDigitsInspect = fractionDigits; if (integerDigits > integerThreshold) { fractionDigitsInspect = 0; } else if (fractionThreshold <= fractionDigits) { fractionDigitsInspect = fractionThreshold + 1; } trailingZeroes = fractionDigits - fractionDigitsInspect; for (i = 0; i < fractionDigitsInspect; i++) { workFractionNumber *= dblBase; workFractionAdjust *= dblBase; workNumber = trio_floor(workFractionNumber + workFractionAdjust); workFractionNumber -= workNumber; offset = (int)trio_fmod(workNumber, dblBase); if (offset == 0) { trailingZeroes++; } else { trailingZeroes = 0; } } expectedWidth -= trailingZeroes; } if (keepDecimalPoint) { expectedWidth += internalDecimalPointLength; } #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) { expectedWidth += TrioCalcThousandSeparatorLength(integerDigits); } #endif if (isNegative || (flags & FLAGS_SHOWSIGN) || (flags & FLAGS_SPACE)) { expectedWidth += sizeof("-") - 1; } exponentDigits = 0; if (flags & FLAGS_FLOAT_E) { exponentDigits = (uExponent == 0) ? 1 : (int)trio_ceil(TrioLogarithm((double)(uExponent + 1), (isHex) ? 10 : base)); } requireTwoDigitExponent = ((base == BASE_DECIMAL) && (exponentDigits == 1)); if (exponentDigits > 0) { expectedWidth += exponentDigits; expectedWidth += (requireTwoDigitExponent ? sizeof("E+0") - 1 : sizeof("E+") - 1); } if (isHex) { expectedWidth += sizeof("0X") - 1; } /* Output prefixing */ if (flags & FLAGS_NILPADDING) { /* Leading zeros must be after sign */ if (isNegative) self->OutStream(self, '-'); else if (flags & FLAGS_SHOWSIGN) self->OutStream(self, '+'); else if (flags & FLAGS_SPACE) self->OutStream(self, ' '); if (isHex) { self->OutStream(self, '0'); self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x'); } if (!(flags & FLAGS_LEFTADJUST)) { for (i = expectedWidth; i < width; i++) { self->OutStream(self, '0'); } } } else { /* Leading spaces must be before sign */ if (!(flags & FLAGS_LEFTADJUST)) { for (i = expectedWidth; i < width; i++) { self->OutStream(self, CHAR_ADJUST); } } if (isNegative) self->OutStream(self, '-'); else if (flags & FLAGS_SHOWSIGN) self->OutStream(self, '+'); else if (flags & FLAGS_SPACE) self->OutStream(self, ' '); if (isHex) { self->OutStream(self, '0'); self->OutStream(self, (flags & FLAGS_UPPER) ? 'X' : 'x'); } } /* Output the integer part and thousand separators */ for (i = 0; i < integerDigits; i++) { workNumber = trio_floor(((integerNumber + integerAdjust) / TrioPower(base, integerDigits - i - 1))); if (i > integerThreshold) { /* Beyond accuracy */ self->OutStream(self, digits[0]); } else { self->OutStream(self, digits[(int)trio_fmod(workNumber, dblBase)]); } #if TRIO_FEATURE_QUOTE if (((flags & (FLAGS_FLOAT_E | FLAGS_QUOTE)) == FLAGS_QUOTE) && TrioFollowedBySeparator(integerDigits - i)) { for (groupingPointer = internalThousandSeparator; *groupingPointer != NIL; groupingPointer++) { self->OutStream(self, *groupingPointer); } } #endif } /* Insert decimal point and build the fraction part */ trailingZeroes = 0; if (keepDecimalPoint) { if (internalDecimalPoint) { self->OutStream(self, internalDecimalPoint); } else { for (i = 0; i < internalDecimalPointLength; i++) { self->OutStream(self, internalDecimalPointString[i]); } } } for (i = 0; i < fractionDigits; i++) { if ((integerDigits > integerThreshold) || (i > fractionThreshold)) { /* Beyond accuracy */ trailingZeroes++; } else { fractionNumber *= dblBase; fractionAdjust *= dblBase; workNumber = trio_floor(fractionNumber + fractionAdjust); if (workNumber > fractionNumber) { /* fractionNumber should never become negative */ fractionNumber = 0.0; fractionAdjust = 0.0; } else { fractionNumber -= workNumber; } offset = (int)trio_fmod(workNumber, dblBase); if (offset == 0) { trailingZeroes++; } else { while (trailingZeroes > 0) { /* Not trailing zeroes after all */ self->OutStream(self, digits[0]); trailingZeroes--; } self->OutStream(self, digits[offset]); } } } if (keepTrailingZeroes) { while (trailingZeroes > 0) { self->OutStream(self, digits[0]); trailingZeroes--; } } /* Output exponent */ if (exponentDigits > 0) { self->OutStream(self, isHex ? ((flags & FLAGS_UPPER) ? 'P' : 'p') : ((flags & FLAGS_UPPER) ? 'E' : 'e')); self->OutStream(self, (isExponentNegative) ? '-' : '+'); /* The exponent must contain at least two digits */ if (requireTwoDigitExponent) self->OutStream(self, '0'); if (isHex) base = 10; exponentBase = (int)TrioPower(base, exponentDigits - 1); for (i = 0; i < exponentDigits; i++) { self->OutStream(self, digits[(uExponent / exponentBase) % base]); exponentBase /= base; } } /* Output trailing spaces */ if (flags & FLAGS_LEFTADJUST) { for (i = expectedWidth; i < width; i++) { self->OutStream(self, CHAR_ADJUST); } } } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * TrioFormatProcess * * Description: * This is the main engine for formatting output */ TRIO_PRIVATE int TrioFormatProcess TRIO_ARGS3((data, format, parameters), trio_class_t* data, TRIO_CONST char* format, trio_parameter_t* parameters) { int i; #if TRIO_FEATURE_ERRNO TRIO_CONST char* string; #endif trio_pointer_t pointer; trio_flags_t flags; int width; int precision; int base; int offset; offset = 0; i = 0; for (;;) { /* Skip the parameter entries */ while (parameters[i].type == FORMAT_PARAMETER) i++; /* Copy non conversion-specifier part of format string */ while (offset < parameters[i].beginOffset) { if (CHAR_IDENTIFIER == format[offset] && CHAR_IDENTIFIER == format[offset + 1]) { data->OutStream(data, CHAR_IDENTIFIER); offset += 2; } else { data->OutStream(data, format[offset++]); } } /* Abort if we reached end of format string */ if (parameters[i].type == FORMAT_SENTINEL) break; /* Ouput parameter */ flags = parameters[i].flags; /* Find width */ width = parameters[i].width; if (flags & FLAGS_WIDTH_PARAMETER) { /* Get width from parameter list */ width = (int)parameters[width].data.number.as_signed; if (width < 0) { /* * A negative width is the same as the - flag and * a positive width. */ flags |= FLAGS_LEFTADJUST; flags &= ~FLAGS_NILPADDING; width = -width; } } /* Find precision */ if (flags & FLAGS_PRECISION) { precision = parameters[i].precision; if (flags & FLAGS_PRECISION_PARAMETER) { /* Get precision from parameter list */ precision = (int)parameters[precision].data.number.as_signed; if (precision < 0) { /* * A negative precision is the same as no * precision */ precision = NO_PRECISION; } } } else { precision = NO_PRECISION; } /* Find base */ if (NO_BASE != parameters[i].baseSpecifier) { /* Base from specifier has priority */ base = parameters[i].baseSpecifier; } else if (flags & FLAGS_BASE_PARAMETER) { /* Get base from parameter list */ base = parameters[i].base; base = (int)parameters[base].data.number.as_signed; } else { /* Use base from format string */ base = parameters[i].base; } switch (parameters[i].type) { case FORMAT_CHAR: #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) data->OutStream(data, CHAR_QUOTE); #endif if (!(flags & FLAGS_LEFTADJUST)) { while (--width > 0) data->OutStream(data, CHAR_ADJUST); } #if TRIO_FEATURE_WIDECHAR if (flags & FLAGS_WIDECHAR) { TrioWriteWideStringCharacter( data, (trio_wchar_t)parameters[i].data.number.as_signed, flags, NO_WIDTH); } else #endif { TrioWriteStringCharacter(data, (int)parameters[i].data.number.as_signed, flags); } if (flags & FLAGS_LEFTADJUST) { while (--width > 0) data->OutStream(data, CHAR_ADJUST); } #if TRIO_FEATURE_QUOTE if (flags & FLAGS_QUOTE) data->OutStream(data, CHAR_QUOTE); #endif break; /* FORMAT_CHAR */ case FORMAT_INT: TrioWriteNumber(data, parameters[i].data.number.as_unsigned, flags, width, precision, base); break; /* FORMAT_INT */ #if TRIO_FEATURE_FLOAT case FORMAT_DOUBLE: TrioWriteDouble(data, parameters[i].data.longdoubleNumber, flags, width, precision, base); break; /* FORMAT_DOUBLE */ #endif case FORMAT_STRING: #if TRIO_FEATURE_WIDECHAR if (flags & FLAGS_WIDECHAR) { TrioWriteWideString(data, parameters[i].data.wstring, flags, width, precision); } else #endif { TrioWriteString(data, parameters[i].data.string, flags, width, precision); } break; /* FORMAT_STRING */ case FORMAT_POINTER: { trio_reference_t reference; reference.data = data; reference.parameter = &parameters[i]; trio_print_pointer(&reference, parameters[i].data.pointer); } break; /* FORMAT_POINTER */ case FORMAT_COUNT: pointer = parameters[i].data.pointer; if (NULL != pointer) { /* * C99 paragraph 7.19.6.1.8 says "the number of * characters written to the output stream so far by * this call", which is data->actually.committed */ #if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER if (flags & FLAGS_SIZE_T) *(size_t*)pointer = (size_t)data->actually.committed; else #endif #if TRIO_FEATURE_PTRDIFF_T if (flags & FLAGS_PTRDIFF_T) *(ptrdiff_t*)pointer = (ptrdiff_t)data->actually.committed; else #endif #if TRIO_FEATURE_INTMAX_T if (flags & FLAGS_INTMAX_T) *(trio_intmax_t*)pointer = (trio_intmax_t)data->actually.committed; else #endif if (flags & FLAGS_QUAD) { *(trio_ulonglong_t*)pointer = (trio_ulonglong_t)data->actually.committed; } else if (flags & FLAGS_LONG) { *(long int*)pointer = (long int)data->actually.committed; } else if (flags & FLAGS_SHORT) { *(short int*)pointer = (short int)data->actually.committed; } else { *(int*)pointer = (int)data->actually.committed; } } break; /* FORMAT_COUNT */ case FORMAT_PARAMETER: break; /* FORMAT_PARAMETER */ #if TRIO_FEATURE_ERRNO case FORMAT_ERRNO: string = trio_error(parameters[i].data.errorNumber); if (string) { TrioWriteString(data, string, flags, width, precision); } else { data->OutStream(data, '#'); TrioWriteNumber(data, (trio_uintmax_t)parameters[i].data.errorNumber, flags, width, precision, BASE_DECIMAL); } break; /* FORMAT_ERRNO */ #endif /* TRIO_FEATURE_ERRNO */ #if TRIO_FEATURE_USER_DEFINED case FORMAT_USER_DEFINED: { trio_reference_t reference; trio_userdef_t* def = NULL; if (parameters[i].flags & FLAGS_USER_DEFINED_PARAMETER) { /* Use handle */ if ((i > 0) || (parameters[i - 1].type == FORMAT_PARAMETER)) def = (trio_userdef_t*)parameters[i - 1].data.pointer; } else { /* Look up namespace */ def = TrioFindNamespace(parameters[i].user_defined.namespace, NULL); } if (def) { reference.data = data; reference.parameter = &parameters[i]; def->callback(&reference); } } break; #endif /* TRIO_FEATURE_USER_DEFINED */ default: break; } /* switch parameter type */ /* Prepare for next */ offset = parameters[i].endOffset; i++; } return data->processed; } /************************************************************************* * TrioFormatRef */ #if TRIO_EXTENSION TRIO_PRIVATE int TrioFormatRef TRIO_ARGS5((reference, format, arglist, argfunc, argarray), trio_reference_t* reference, TRIO_CONST char* format, va_list arglist, trio_argfunc_t argfunc, trio_pointer_t* argarray) { int status; trio_parameter_t parameters[MAX_PARAMETERS]; status = TrioParse(TYPE_PRINT, format, parameters, arglist, argfunc, argarray); if (status < 0) return status; status = TrioFormatProcess(reference->data, format, parameters); if (reference->data->error != 0) { status = reference->data->error; } return status; } #endif /* TRIO_EXTENSION */ /************************************************************************* * TrioFormat */ TRIO_PRIVATE int TrioFormat TRIO_ARGS7((destination, destinationSize, OutStream, format, arglist, argfunc, argarray), trio_pointer_t destination, size_t destinationSize, void(*OutStream) TRIO_PROTO((trio_class_t*, int)), TRIO_CONST char* format, va_list arglist, trio_argfunc_t argfunc, trio_pointer_t* argarray) { int status; trio_class_t data; trio_parameter_t parameters[MAX_PARAMETERS]; assert(VALID(OutStream)); assert(VALID(format)); memset(&data, 0, sizeof(data)); data.OutStream = OutStream; data.location = destination; data.max = destinationSize; data.error = 0; #if defined(USE_LOCALE) if (NULL == internalLocaleValues) { TrioSetLocale(); } #endif status = TrioParse(TYPE_PRINT, format, parameters, arglist, argfunc, argarray); if (status < 0) return status; status = TrioFormatProcess(&data, format, parameters); if (data.error != 0) { status = data.error; } return status; } /************************************************************************* * TrioOutStreamFile */ #if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO TRIO_PRIVATE void TrioOutStreamFile TRIO_ARGS2((self, output), trio_class_t* self, int output) { FILE* file; assert(VALID(self)); assert(VALID(self->location)); file = (FILE*)self->location; self->processed++; if (fputc(output, file) == EOF) { self->error = TRIO_ERROR_RETURN(TRIO_EOF, 0); } else { self->actually.committed++; } } #endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */ /************************************************************************* * TrioOutStreamFileDescriptor */ #if TRIO_FEATURE_FD TRIO_PRIVATE void TrioOutStreamFileDescriptor TRIO_ARGS2((self, output), trio_class_t* self, int output) { int fd; char ch; assert(VALID(self)); fd = *((int*)self->location); ch = (char)output; self->processed++; if (write(fd, &ch, sizeof(char)) == -1) { self->error = TRIO_ERROR_RETURN(TRIO_ERRNO, 0); } else { self->actually.committed++; } } #endif /* TRIO_FEATURE_FD */ /************************************************************************* * TrioOutStreamCustom */ #if TRIO_FEATURE_CLOSURE TRIO_PRIVATE void TrioOutStreamCustom TRIO_ARGS2((self, output), trio_class_t* self, int output) { int status; trio_custom_t* data; assert(VALID(self)); assert(VALID(self->location)); data = (trio_custom_t*)self->location; if (data->stream.out) { status = (data->stream.out)(data->closure, output); if (status >= 0) { self->actually.committed++; } else { if (self->error == 0) { self->error = TRIO_ERROR_RETURN(TRIO_ECUSTOM, -status); } } } self->processed++; } #endif /* TRIO_FEATURE_CLOSURE */ /************************************************************************* * TrioOutStreamString */ TRIO_PRIVATE void TrioOutStreamString TRIO_ARGS2((self, output), trio_class_t* self, int output) { char** buffer; assert(VALID(self)); assert(VALID(self->location)); buffer = (char**)self->location; **buffer = (char)output; (*buffer)++; self->processed++; self->actually.committed++; } /************************************************************************* * TrioOutStreamStringMax */ TRIO_PRIVATE void TrioOutStreamStringMax TRIO_ARGS2((self, output), trio_class_t* self, int output) { char** buffer; assert(VALID(self)); assert(VALID(self->location)); buffer = (char**)self->location; if (self->processed < self->max) { **buffer = (char)output; (*buffer)++; self->actually.committed++; } self->processed++; } /************************************************************************* * TrioOutStreamStringDynamic */ #if TRIO_FEATURE_DYNAMICSTRING TRIO_PRIVATE void TrioOutStreamStringDynamic TRIO_ARGS2((self, output), trio_class_t* self, int output) { assert(VALID(self)); assert(VALID(self->location)); if (self->error == 0) { trio_xstring_append_char((trio_string_t*)self->location, (char)output); self->actually.committed++; } /* The processed variable must always be increased */ self->processed++; } #endif /* TRIO_FEATURE_DYNAMICSTRING */ /************************************************************************* * TrioArrayGetter */ static trio_pointer_t TrioArrayGetter(trio_pointer_t context, int index, int type) { /* Utility function for the printfv family */ trio_pointer_t* argarray = (trio_pointer_t*)context; return argarray[index]; } /************************************************************************* * * Formatted printing functions * ************************************************************************/ /** @addtogroup Printf @{ */ /************************************************************************* * printf */ /** Print to standard output stream. @param format Formatting string. @param ... Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_STDIO TRIO_PUBLIC int trio_printf TRIO_VARGS2((format, va_alist), TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(format)); TRIO_VA_START(args, format); status = TrioFormat(stdout, 0, TrioOutStreamFile, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_STDIO */ /** Print to standard output stream. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_STDIO TRIO_PUBLIC int trio_vprintf TRIO_ARGS2((format, args), TRIO_CONST char* format, va_list args) { assert(VALID(format)); return TrioFormat(stdout, 0, TrioOutStreamFile, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_STDIO */ /** Print to standard output stream. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_STDIO TRIO_PUBLIC int trio_printfv TRIO_ARGS2((format, args), TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(format)); return TrioFormat(stdout, 0, TrioOutStreamFile, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_STDIO */ /************************************************************************* * fprintf */ /** Print to file. @param file File pointer. @param format Formatting string. @param ... Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_FILE TRIO_PUBLIC int trio_fprintf TRIO_VARGS3((file, format, va_alist), FILE* file, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(file)); assert(VALID(format)); TRIO_VA_START(args, format); status = TrioFormat(file, 0, TrioOutStreamFile, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_FILE */ /** Print to file. @param file File pointer. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_FILE TRIO_PUBLIC int trio_vfprintf TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format, va_list args) { assert(VALID(file)); assert(VALID(format)); return TrioFormat(file, 0, TrioOutStreamFile, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_FILE */ /** Print to file. @param file File pointer. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_FILE TRIO_PUBLIC int trio_fprintfv TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(file)); assert(VALID(format)); return TrioFormat(file, 0, TrioOutStreamFile, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_FILE */ /************************************************************************* * dprintf */ /** Print to file descriptor. @param fd File descriptor. @param format Formatting string. @param ... Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_FD TRIO_PUBLIC int trio_dprintf TRIO_VARGS3((fd, format, va_alist), int fd, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(format)); TRIO_VA_START(args, format); status = TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_FD */ /** Print to file descriptor. @param fd File descriptor. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_FD TRIO_PUBLIC int trio_vdprintf TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format, va_list args) { assert(VALID(format)); return TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_FD */ /** Print to file descriptor. @param fd File descriptor. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_FD TRIO_PUBLIC int trio_dprintfv TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(format)); return TrioFormat(&fd, 0, TrioOutStreamFileDescriptor, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_FD */ /************************************************************************* * cprintf */ #if TRIO_FEATURE_CLOSURE TRIO_PUBLIC int trio_cprintf TRIO_VARGS4((stream, closure, format, va_alist), trio_outstream_t stream, trio_pointer_t closure, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); TRIO_VA_START(args, format); data.stream.out = stream; data.closure = closure; status = TrioFormat(&data, 0, TrioOutStreamCustom, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_CLOSURE */ #if TRIO_FEATURE_CLOSURE TRIO_PUBLIC int trio_vcprintf TRIO_ARGS4((stream, closure, format, args), trio_outstream_t stream, trio_pointer_t closure, TRIO_CONST char* format, va_list args) { trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); data.stream.out = stream; data.closure = closure; return TrioFormat(&data, 0, TrioOutStreamCustom, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_CLOSURE */ #if TRIO_FEATURE_CLOSURE TRIO_PUBLIC int trio_cprintfv TRIO_ARGS4((stream, closure, format, args), trio_outstream_t stream, trio_pointer_t closure, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); data.stream.out = stream; data.closure = closure; return TrioFormat(&data, 0, TrioOutStreamCustom, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_CLOSURE */ #if TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC TRIO_PUBLIC int trio_cprintff TRIO_ARGS5((stream, closure, format, argfunc, context), trio_outstream_t stream, trio_pointer_t closure, TRIO_CONST char* format, trio_argfunc_t argfunc, trio_pointer_t context) { static va_list unused; trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); assert(VALID(argfunc)); data.stream.out = stream; data.closure = closure; return TrioFormat(&data, 0, TrioOutStreamCustom, format, unused, argfunc, (trio_pointer_t*)context); } #endif /* TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC */ /************************************************************************* * sprintf */ /** Print to string. @param buffer Output string. @param format Formatting string. @param ... Arguments. @return Number of printed characters. */ TRIO_PUBLIC int trio_sprintf TRIO_VARGS3((buffer, format, va_alist), char* buffer, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(buffer)); assert(VALID(format)); TRIO_VA_START(args, format); status = TrioFormat(&buffer, 0, TrioOutStreamString, format, args, NULL, NULL); *buffer = NIL; /* Terminate with NIL character */ TRIO_VA_END(args); return status; } /** Print to string. @param buffer Output string. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ TRIO_PUBLIC int trio_vsprintf TRIO_ARGS3((buffer, format, args), char* buffer, TRIO_CONST char* format, va_list args) { int status; assert(VALID(buffer)); assert(VALID(format)); status = TrioFormat(&buffer, 0, TrioOutStreamString, format, args, NULL, NULL); *buffer = NIL; return status; } /** Print to string. @param buffer Output string. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ TRIO_PUBLIC int trio_sprintfv TRIO_ARGS3((buffer, format, args), char* buffer, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; int status; assert(VALID(buffer)); assert(VALID(format)); status = TrioFormat(&buffer, 0, TrioOutStreamString, format, unused, TrioArrayGetter, args); *buffer = NIL; return status; } /************************************************************************* * snprintf */ /** Print at most @p max characters to string. @param buffer Output string. @param max Maximum number of characters to print. @param format Formatting string. @param ... Arguments. @return Number of printed characters. */ TRIO_PUBLIC int trio_snprintf TRIO_VARGS4((buffer, max, format, va_alist), char* buffer, size_t max, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(buffer) || (max == 0)); assert(VALID(format)); TRIO_VA_START(args, format); status = TrioFormat(&buffer, max > 0 ? max - 1 : 0, TrioOutStreamStringMax, format, args, NULL, NULL); if (max > 0) *buffer = NIL; TRIO_VA_END(args); return status; } /** Print at most @p max characters to string. @param buffer Output string. @param max Maximum number of characters to print. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ TRIO_PUBLIC int trio_vsnprintf TRIO_ARGS4((buffer, max, format, args), char* buffer, size_t max, TRIO_CONST char* format, va_list args) { int status; assert(VALID(buffer) || (max == 0)); assert(VALID(format)); status = TrioFormat(&buffer, max > 0 ? max - 1 : 0, TrioOutStreamStringMax, format, args, NULL, NULL); if (max > 0) *buffer = NIL; return status; } /** Print at most @p max characters to string. @param buffer Output string. @param max Maximum number of characters to print. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ TRIO_PUBLIC int trio_snprintfv TRIO_ARGS4((buffer, max, format, args), char* buffer, size_t max, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; int status; assert(VALID(buffer) || (max == 0)); assert(VALID(format)); status = TrioFormat(&buffer, max > 0 ? max - 1 : 0, TrioOutStreamStringMax, format, unused, TrioArrayGetter, args); if (max > 0) *buffer = NIL; return status; } /************************************************************************* * snprintfcat * Appends the new string to the buffer string overwriting the '\0' * character at the end of buffer. */ #if TRIO_EXTENSION TRIO_PUBLIC int trio_snprintfcat TRIO_VARGS4((buffer, max, format, va_alist), char* buffer, size_t max, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; size_t buf_len; TRIO_VA_START(args, format); assert(VALID(buffer)); assert(VALID(format)); buf_len = trio_length(buffer); buffer = &buffer[buf_len]; status = TrioFormat(&buffer, max - 1 - buf_len, TrioOutStreamStringMax, format, args, NULL, NULL); TRIO_VA_END(args); *buffer = NIL; return status; } #endif #if TRIO_EXTENSION TRIO_PUBLIC int trio_vsnprintfcat TRIO_ARGS4((buffer, max, format, args), char* buffer, size_t max, TRIO_CONST char* format, va_list args) { int status; size_t buf_len; assert(VALID(buffer)); assert(VALID(format)); buf_len = trio_length(buffer); buffer = &buffer[buf_len]; status = TrioFormat(&buffer, max - 1 - buf_len, TrioOutStreamStringMax, format, args, NULL, NULL); *buffer = NIL; return status; } #endif /************************************************************************* * trio_aprintf */ #if TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING TRIO_PUBLIC char* trio_aprintf TRIO_VARGS2((format, va_alist), TRIO_CONST char* format, TRIO_VA_DECL) { va_list args; trio_string_t* info; char* result = NULL; assert(VALID(format)); info = trio_xstring_duplicate(""); if (info) { TRIO_VA_START(args, format); (void)TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL); TRIO_VA_END(args); trio_string_terminate(info); result = trio_string_extract(info); trio_string_destroy(info); } return result; } #endif /* TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING */ #if TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING TRIO_PUBLIC char* trio_vaprintf TRIO_ARGS2((format, args), TRIO_CONST char* format, va_list args) { trio_string_t* info; char* result = NULL; assert(VALID(format)); info = trio_xstring_duplicate(""); if (info) { (void)TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL); trio_string_terminate(info); result = trio_string_extract(info); trio_string_destroy(info); } return result; } #endif /* TRIO_DEPRECATED && TRIO_FEATURE_DYNAMICSTRING */ /** Allocate and print to string. The memory allocated and returned by @p result must be freed by the calling application. @param result Output string. @param format Formatting string. @param ... Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_DYNAMICSTRING TRIO_PUBLIC int trio_asprintf TRIO_VARGS3((result, format, va_alist), char** result, TRIO_CONST char* format, TRIO_VA_DECL) { va_list args; int status; trio_string_t* info; assert(VALID(format)); *result = NULL; info = trio_xstring_duplicate(""); if (info == NULL) { status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0); } else { TRIO_VA_START(args, format); status = TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL); TRIO_VA_END(args); if (status >= 0) { trio_string_terminate(info); *result = trio_string_extract(info); } trio_string_destroy(info); } return status; } #endif /* TRIO_FEATURE_DYNAMICSTRING */ /** Allocate and print to string. The memory allocated and returned by @p result must be freed by the calling application. @param result Output string. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_DYNAMICSTRING TRIO_PUBLIC int trio_vasprintf TRIO_ARGS3((result, format, args), char** result, TRIO_CONST char* format, va_list args) { int status; trio_string_t* info; assert(VALID(format)); *result = NULL; info = trio_xstring_duplicate(""); if (info == NULL) { status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0); } else { status = TrioFormat(info, 0, TrioOutStreamStringDynamic, format, args, NULL, NULL); if (status >= 0) { trio_string_terminate(info); *result = trio_string_extract(info); } trio_string_destroy(info); } return status; } #endif /* TRIO_FEATURE_DYNAMICSTRING */ /** Allocate and print to string. The memory allocated and returned by @p result must be freed by the calling application. @param result Output string. @param format Formatting string. @param args Arguments. @return Number of printed characters. */ #if TRIO_FEATURE_DYNAMICSTRING TRIO_PUBLIC int trio_asprintfv TRIO_ARGS3((result, format, args), char** result, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; int status; trio_string_t* info; assert(VALID(format)); *result = NULL; info = trio_xstring_duplicate(""); if (info == NULL) { status = TRIO_ERROR_RETURN(TRIO_ENOMEM, 0); } else { status = TrioFormat(info, 0, TrioOutStreamStringDynamic, format, unused, TrioArrayGetter, args); if (status >= 0) { trio_string_terminate(info); *result = trio_string_extract(info); } trio_string_destroy(info); } return status; } #endif /* TRIO_FEATURE_DYNAMICSTRING */ #if defined(TRIO_DOCUMENTATION) #include "doc/doc_printf.h" #endif /** @} End of Printf documentation module */ /************************************************************************* * * CALLBACK * ************************************************************************/ #if defined(TRIO_DOCUMENTATION) #include "doc/doc_register.h" #endif /** @addtogroup UserDefined @{ */ #if TRIO_FEATURE_USER_DEFINED /************************************************************************* * trio_register */ /** Register new user-defined specifier. @param callback @param name @return Handle. */ TRIO_PUBLIC trio_pointer_t trio_register TRIO_ARGS2((callback, name), trio_callback_t callback, TRIO_CONST char* name) { trio_userdef_t* def; trio_userdef_t* prev = NULL; if (callback == NULL) return NULL; if (name) { /* Handle built-in namespaces */ if (name[0] == ':') { if (trio_equal(name, ":enter")) { internalEnterCriticalRegion = callback; } else if (trio_equal(name, ":leave")) { internalLeaveCriticalRegion = callback; } return NULL; } /* Bail out if namespace is too long */ if (trio_length_max(name, MAX_USER_NAME) >= MAX_USER_NAME) return NULL; /* Bail out if namespace already is registered */ def = TrioFindNamespace(name, &prev); if (def) return NULL; } def = (trio_userdef_t*)TRIO_MALLOC(sizeof(trio_userdef_t)); if (def) { if (internalEnterCriticalRegion) (void)internalEnterCriticalRegion(NULL); if (name) { /* Link into internal list */ if (prev == NULL) internalUserDef = def; else prev->next = def; } /* Initialize */ def->callback = callback; def->name = (name == NULL) ? NULL : trio_duplicate(name); def->next = NULL; if (internalLeaveCriticalRegion) (void)internalLeaveCriticalRegion(NULL); } return (trio_pointer_t)def; } /** Unregister an existing user-defined specifier. @param handle */ void trio_unregister TRIO_ARGS1((handle), trio_pointer_t handle) { trio_userdef_t* self = (trio_userdef_t*)handle; trio_userdef_t* def; trio_userdef_t* prev = NULL; assert(VALID(self)); if (self->name) { def = TrioFindNamespace(self->name, &prev); if (def) { if (internalEnterCriticalRegion) (void)internalEnterCriticalRegion(NULL); if (prev == NULL) internalUserDef = internalUserDef->next; else prev->next = def->next; if (internalLeaveCriticalRegion) (void)internalLeaveCriticalRegion(NULL); } trio_destroy(self->name); } TRIO_FREE(self); } /************************************************************************* * trio_get_format [public] */ TRIO_CONST char* trio_get_format TRIO_ARGS1((ref), trio_pointer_t ref) { #if TRIO_FEATURE_USER_DEFINED assert(((trio_reference_t*)ref)->parameter->type == FORMAT_USER_DEFINED); #endif return (((trio_reference_t*)ref)->parameter->user_data); } /************************************************************************* * trio_get_argument [public] */ trio_pointer_t trio_get_argument TRIO_ARGS1((ref), trio_pointer_t ref) { #if TRIO_FEATURE_USER_DEFINED assert(((trio_reference_t*)ref)->parameter->type == FORMAT_USER_DEFINED); #endif return ((trio_reference_t*)ref)->parameter->data.pointer; } /************************************************************************* * trio_get_width / trio_set_width [public] */ int trio_get_width TRIO_ARGS1((ref), trio_pointer_t ref) { return ((trio_reference_t*)ref)->parameter->width; } void trio_set_width TRIO_ARGS2((ref, width), trio_pointer_t ref, int width) { ((trio_reference_t*)ref)->parameter->width = width; } /************************************************************************* * trio_get_precision / trio_set_precision [public] */ int trio_get_precision TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->precision); } void trio_set_precision TRIO_ARGS2((ref, precision), trio_pointer_t ref, int precision) { ((trio_reference_t*)ref)->parameter->precision = precision; } /************************************************************************* * trio_get_base / trio_set_base [public] */ int trio_get_base TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->base); } void trio_set_base TRIO_ARGS2((ref, base), trio_pointer_t ref, int base) { ((trio_reference_t*)ref)->parameter->base = base; } /************************************************************************* * trio_get_long / trio_set_long [public] */ int trio_get_long TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_LONG) ? TRUE : FALSE; } void trio_set_long TRIO_ARGS2((ref, is_long), trio_pointer_t ref, int is_long) { if (is_long) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_LONG; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_LONG; } /************************************************************************* * trio_get_longlong / trio_set_longlong [public] */ int trio_get_longlong TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_QUAD) ? TRUE : FALSE; } void trio_set_longlong TRIO_ARGS2((ref, is_longlong), trio_pointer_t ref, int is_longlong) { if (is_longlong) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_QUAD; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_QUAD; } /************************************************************************* * trio_get_longdouble / trio_set_longdouble [public] */ #if TRIO_FEATURE_FLOAT int trio_get_longdouble TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_LONGDOUBLE) ? TRUE : FALSE; } void trio_set_longdouble TRIO_ARGS2((ref, is_longdouble), trio_pointer_t ref, int is_longdouble) { if (is_longdouble) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_LONGDOUBLE; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_LONGDOUBLE; } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * trio_get_short / trio_set_short [public] */ int trio_get_short TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SHORT) ? TRUE : FALSE; } void trio_set_short TRIO_ARGS2((ref, is_short), trio_pointer_t ref, int is_short) { if (is_short) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_SHORT; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SHORT; } /************************************************************************* * trio_get_shortshort / trio_set_shortshort [public] */ int trio_get_shortshort TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SHORTSHORT) ? TRUE : FALSE; } void trio_set_shortshort TRIO_ARGS2((ref, is_shortshort), trio_pointer_t ref, int is_shortshort) { if (is_shortshort) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_SHORTSHORT; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SHORTSHORT; } /************************************************************************* * trio_get_alternative / trio_set_alternative [public] */ int trio_get_alternative TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_ALTERNATIVE) ? TRUE : FALSE; } void trio_set_alternative TRIO_ARGS2((ref, is_alternative), trio_pointer_t ref, int is_alternative) { if (is_alternative) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_ALTERNATIVE; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_ALTERNATIVE; } /************************************************************************* * trio_get_alignment / trio_set_alignment [public] */ int trio_get_alignment TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_LEFTADJUST) ? TRUE : FALSE; } void trio_set_alignment TRIO_ARGS2((ref, is_leftaligned), trio_pointer_t ref, int is_leftaligned) { if (is_leftaligned) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_LEFTADJUST; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_LEFTADJUST; } /************************************************************************* * trio_get_spacing /trio_set_spacing [public] */ int trio_get_spacing TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SPACE) ? TRUE : FALSE; } void trio_set_spacing TRIO_ARGS2((ref, is_space), trio_pointer_t ref, int is_space) { if (is_space) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_SPACE; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SPACE; } /************************************************************************* * trio_get_sign / trio_set_sign [public] */ int trio_get_sign TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SHOWSIGN) ? TRUE : FALSE; } void trio_set_sign TRIO_ARGS2((ref, is_sign), trio_pointer_t ref, int is_sign) { if (is_sign) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_SHOWSIGN; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SHOWSIGN; } /************************************************************************* * trio_get_padding / trio_set_padding [public] */ int trio_get_padding TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_NILPADDING) ? TRUE : FALSE; } void trio_set_padding TRIO_ARGS2((ref, is_padding), trio_pointer_t ref, int is_padding) { if (is_padding) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_NILPADDING; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_NILPADDING; } /************************************************************************* * trio_get_quote / trio_set_quote [public] */ #if TRIO_FEATURE_QUOTE int trio_get_quote TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_QUOTE) ? TRUE : FALSE; } void trio_set_quote TRIO_ARGS2((ref, is_quote), trio_pointer_t ref, int is_quote) { if (is_quote) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_QUOTE; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_QUOTE; } #endif /* TRIO_FEATURE_QUOTE */ /************************************************************************* * trio_get_upper / trio_set_upper [public] */ int trio_get_upper TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_UPPER) ? TRUE : FALSE; } void trio_set_upper TRIO_ARGS2((ref, is_upper), trio_pointer_t ref, int is_upper) { if (is_upper) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_UPPER; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_UPPER; } /************************************************************************* * trio_get_largest / trio_set_largest [public] */ #if TRIO_FEATURE_INTMAX_T int trio_get_largest TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_INTMAX_T) ? TRUE : FALSE; } void trio_set_largest TRIO_ARGS2((ref, is_largest), trio_pointer_t ref, int is_largest) { if (is_largest) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_INTMAX_T; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_INTMAX_T; } #endif /* TRIO_FEATURE_INTMAX_T */ /************************************************************************* * trio_get_ptrdiff / trio_set_ptrdiff [public] */ #if TRIO_FEATURE_PTRDIFF_T int trio_get_ptrdiff TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_PTRDIFF_T) ? TRUE : FALSE; } void trio_set_ptrdiff TRIO_ARGS2((ref, is_ptrdiff), trio_pointer_t ref, int is_ptrdiff) { if (is_ptrdiff) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_PTRDIFF_T; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_PTRDIFF_T; } #endif /* TRIO_FEATURE_PTRDIFF_T */ /************************************************************************* * trio_get_size / trio_set_size [public] */ #if TRIO_FEATURE_SIZE_T int trio_get_size TRIO_ARGS1((ref), trio_pointer_t ref) { return (((trio_reference_t*)ref)->parameter->flags & FLAGS_SIZE_T) ? TRUE : FALSE; } void trio_set_size TRIO_ARGS2((ref, is_size), trio_pointer_t ref, int is_size) { if (is_size) ((trio_reference_t*)ref)->parameter->flags |= FLAGS_SIZE_T; else ((trio_reference_t*)ref)->parameter->flags &= ~FLAGS_SIZE_T; } #endif /* TRIO_FEATURE_SIZE_T */ /************************************************************************* * trio_print_int [public] */ void trio_print_int TRIO_ARGS2((ref, number), trio_pointer_t ref, int number) { trio_reference_t* self = (trio_reference_t*)ref; TrioWriteNumber(self->data, (trio_uintmax_t)number, self->parameter->flags, self->parameter->width, self->parameter->precision, self->parameter->base); } /************************************************************************* * trio_print_uint [public] */ void trio_print_uint TRIO_ARGS2((ref, number), trio_pointer_t ref, unsigned int number) { trio_reference_t* self = (trio_reference_t*)ref; TrioWriteNumber(self->data, (trio_uintmax_t)number, self->parameter->flags | FLAGS_UNSIGNED, self->parameter->width, self->parameter->precision, self->parameter->base); } /************************************************************************* * trio_print_double [public] */ #if TRIO_FEATURE_FLOAT void trio_print_double TRIO_ARGS2((ref, number), trio_pointer_t ref, double number) { trio_reference_t* self = (trio_reference_t*)ref; TrioWriteDouble(self->data, number, self->parameter->flags, self->parameter->width, self->parameter->precision, self->parameter->base); } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * trio_print_string [public] */ void trio_print_string TRIO_ARGS2((ref, string), trio_pointer_t ref, TRIO_CONST char* string) { trio_reference_t* self = (trio_reference_t*)ref; TrioWriteString(self->data, string, self->parameter->flags, self->parameter->width, self->parameter->precision); } /************************************************************************* * trio_print_ref [public] */ int trio_print_ref TRIO_VARGS3((ref, format, va_alist), trio_pointer_t ref, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list arglist; assert(VALID(format)); TRIO_VA_START(arglist, format); status = TrioFormatRef((trio_reference_t*)ref, format, arglist, NULL, NULL); TRIO_VA_END(arglist); return status; } /************************************************************************* * trio_vprint_ref [public] */ int trio_vprint_ref TRIO_ARGS3((ref, format, arglist), trio_pointer_t ref, TRIO_CONST char* format, va_list arglist) { assert(VALID(format)); return TrioFormatRef((trio_reference_t*)ref, format, arglist, NULL, NULL); } /************************************************************************* * trio_printv_ref [public] */ int trio_printv_ref TRIO_ARGS3((ref, format, argarray), trio_pointer_t ref, TRIO_CONST char* format, trio_pointer_t* argarray) { static va_list unused; assert(VALID(format)); return TrioFormatRef((trio_reference_t*)ref, format, unused, TrioArrayGetter, argarray); } #endif /************************************************************************* * trio_print_pointer [public] */ void trio_print_pointer TRIO_ARGS2((ref, pointer), trio_pointer_t ref, trio_pointer_t pointer) { trio_reference_t* self = (trio_reference_t*)ref; trio_flags_t flags; trio_uintmax_t number; if (NULL == pointer) { TRIO_CONST char* string = internalNullString; while (*string) self->data->OutStream(self->data, *string++); } else { /* * The subtraction of the null pointer is a workaround * to avoid a compiler warning. The performance overhead * is negligible (and likely to be removed by an * optimizing compiler). The (char *) casting is done * to please ANSI C++. */ number = (trio_uintmax_t)((char*)pointer - (char*)0); /* Shrink to size of pointer */ number &= (trio_uintmax_t)-1; flags = self->parameter->flags; flags |= (FLAGS_UNSIGNED | FLAGS_ALTERNATIVE | FLAGS_NILPADDING); TrioWriteNumber(self->data, number, flags, POINTER_WIDTH, NO_PRECISION, BASE_HEX); } } /** @} End of UserDefined documentation module */ /************************************************************************* * * LOCALES * ************************************************************************/ /************************************************************************* * trio_locale_set_decimal_point * * Decimal point can only be one character. The input argument is a * string to enable multibyte characters. At most MB_LEN_MAX characters * will be used. */ #if TRIO_FEATURE_LOCALE TRIO_PUBLIC void trio_locale_set_decimal_point TRIO_ARGS1((decimalPoint), char* decimalPoint) { #if defined(USE_LOCALE) if (NULL == internalLocaleValues) { TrioSetLocale(); } #endif internalDecimalPointLength = trio_length(decimalPoint); if (internalDecimalPointLength == 1) { internalDecimalPoint = *decimalPoint; } else { internalDecimalPoint = NIL; trio_copy_max(internalDecimalPointString, sizeof(internalDecimalPointString), decimalPoint); } } #endif /************************************************************************* * trio_locale_set_thousand_separator * * See trio_locale_set_decimal_point */ #if TRIO_FEATURE_LOCALE || TRIO_EXTENSION TRIO_PUBLIC void trio_locale_set_thousand_separator TRIO_ARGS1((thousandSeparator), char* thousandSeparator) { #if defined(USE_LOCALE) if (NULL == internalLocaleValues) { TrioSetLocale(); } #endif trio_copy_max(internalThousandSeparator, sizeof(internalThousandSeparator), thousandSeparator); internalThousandSeparatorLength = trio_length(internalThousandSeparator); } #endif /************************************************************************* * trio_locale_set_grouping * * Array of bytes. Reversed order. * * CHAR_MAX : No further grouping * 0 : Repeat last group for the remaining digits (not necessary * as C strings are zero-terminated) * n : Set current group to n * * Same order as the grouping attribute in LC_NUMERIC. */ #if TRIO_FEATURE_LOCALE || TRIO_EXTENSION TRIO_PUBLIC void trio_locale_set_grouping TRIO_ARGS1((grouping), char* grouping) { #if defined(USE_LOCALE) if (NULL == internalLocaleValues) { TrioSetLocale(); } #endif trio_copy_max(internalGrouping, sizeof(internalGrouping), grouping); } #endif /************************************************************************* * * SCANNING * ************************************************************************/ #if TRIO_FEATURE_SCANF /************************************************************************* * TrioSkipWhitespaces */ TRIO_PRIVATE int TrioSkipWhitespaces TRIO_ARGS1((self), trio_class_t* self) { int ch; ch = self->current; while (isspace(ch)) { self->InStream(self, &ch); } return ch; } /************************************************************************* * TrioGetCollation */ #if TRIO_EXTENSION TRIO_PRIVATE void TrioGetCollation(TRIO_NOARGS) { int i; int j; int k; char first[2]; char second[2]; /* This is computationally expensive */ first[1] = NIL; second[1] = NIL; for (i = 0; i < MAX_CHARACTER_CLASS; i++) { k = 0; first[0] = (char)i; for (j = 0; j < MAX_CHARACTER_CLASS; j++) { second[0] = (char)j; if (trio_equal_locale(first, second)) internalCollationArray[i][k++] = (char)j; } internalCollationArray[i][k] = NIL; } } #endif /************************************************************************* * TrioGetCharacterClass * * FIXME: * multibyte */ TRIO_PRIVATE int TrioGetCharacterClass TRIO_ARGS4((format, offsetPointer, flagsPointer, characterclass), TRIO_CONST char* format, int* offsetPointer, trio_flags_t* flagsPointer, int* characterclass) { int offset = *offsetPointer; int i; char ch; char range_begin; char range_end; *flagsPointer &= ~FLAGS_EXCLUDE; if (format[offset] == QUALIFIER_CIRCUMFLEX) { *flagsPointer |= FLAGS_EXCLUDE; offset++; } /* * If the ungroup character is at the beginning of the scanlist, * it will be part of the class, and a second ungroup character * must follow to end the group. */ if (format[offset] == SPECIFIER_UNGROUP) { characterclass[(int)SPECIFIER_UNGROUP]++; offset++; } /* * Minus is used to specify ranges. To include minus in the class, * it must be at the beginning of the list */ if (format[offset] == QUALIFIER_MINUS) { characterclass[(int)QUALIFIER_MINUS]++; offset++; } /* Collect characters */ for (ch = format[offset]; (ch != SPECIFIER_UNGROUP) && (ch != NIL); ch = format[++offset]) { switch (ch) { case QUALIFIER_MINUS: /* Scanlist ranges */ /* * Both C99 and UNIX98 describes ranges as implementation- * defined. * * We support the following behaviour (although this may * change as we become wiser) * - only increasing ranges, ie. [a-b] but not [b-a] * - transitive ranges, ie. [a-b-c] == [a-c] * - trailing minus, ie. [a-] is interpreted as an 'a' * and a '-' * - duplicates (although we can easily convert these * into errors) */ range_begin = format[offset - 1]; range_end = format[++offset]; if (range_end == SPECIFIER_UNGROUP) { /* Trailing minus is included */ characterclass[(int)ch]++; ch = range_end; break; /* for */ } if (range_end == NIL) return TRIO_ERROR_RETURN(TRIO_EINVAL, offset); if (range_begin > range_end) return TRIO_ERROR_RETURN(TRIO_ERANGE, offset); for (i = (int)range_begin; i <= (int)range_end; i++) characterclass[i]++; ch = range_end; break; #if TRIO_EXTENSION case SPECIFIER_GROUP: switch (format[offset + 1]) { case QUALIFIER_DOT: /* Collating symbol */ /* * FIXME: This will be easier to implement when multibyte * characters have been implemented. Until now, we ignore * this feature. */ for (i = offset + 2;; i++) { if (format[i] == NIL) /* Error in syntax */ return -1; else if (format[i] == QUALIFIER_DOT) break; /* for */ } if (format[++i] != SPECIFIER_UNGROUP) return -1; offset = i; break; case QUALIFIER_EQUAL: /* Equivalence class expressions */ { unsigned int j; unsigned int k; if (internalCollationUnconverted) { /* Lazy evaluation of collation array */ TrioGetCollation(); internalCollationUnconverted = FALSE; } for (i = offset + 2;; i++) { if (format[i] == NIL) /* Error in syntax */ return -1; else if (format[i] == QUALIFIER_EQUAL) break; /* for */ else { /* Mark any equivalent character */ k = (unsigned int)format[i]; for (j = 0; internalCollationArray[k][j] != NIL; j++) characterclass[(int)internalCollationArray[k][j]]++; } } if (format[++i] != SPECIFIER_UNGROUP) return -1; offset = i; } break; case QUALIFIER_COLON: /* Character class expressions */ if (trio_equal_max(CLASS_ALNUM, sizeof(CLASS_ALNUM) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isalnum(i)) characterclass[i]++; offset += sizeof(CLASS_ALNUM) - 1; } else if (trio_equal_max(CLASS_ALPHA, sizeof(CLASS_ALPHA) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isalpha(i)) characterclass[i]++; offset += sizeof(CLASS_ALPHA) - 1; } else if (trio_equal_max(CLASS_CNTRL, sizeof(CLASS_CNTRL) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (iscntrl(i)) characterclass[i]++; offset += sizeof(CLASS_CNTRL) - 1; } else if (trio_equal_max(CLASS_DIGIT, sizeof(CLASS_DIGIT) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isdigit(i)) characterclass[i]++; offset += sizeof(CLASS_DIGIT) - 1; } else if (trio_equal_max(CLASS_GRAPH, sizeof(CLASS_GRAPH) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isgraph(i)) characterclass[i]++; offset += sizeof(CLASS_GRAPH) - 1; } else if (trio_equal_max(CLASS_LOWER, sizeof(CLASS_LOWER) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (islower(i)) characterclass[i]++; offset += sizeof(CLASS_LOWER) - 1; } else if (trio_equal_max(CLASS_PRINT, sizeof(CLASS_PRINT) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isprint(i)) characterclass[i]++; offset += sizeof(CLASS_PRINT) - 1; } else if (trio_equal_max(CLASS_PUNCT, sizeof(CLASS_PUNCT) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (ispunct(i)) characterclass[i]++; offset += sizeof(CLASS_PUNCT) - 1; } else if (trio_equal_max(CLASS_SPACE, sizeof(CLASS_SPACE) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isspace(i)) characterclass[i]++; offset += sizeof(CLASS_SPACE) - 1; } else if (trio_equal_max(CLASS_UPPER, sizeof(CLASS_UPPER) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isupper(i)) characterclass[i]++; offset += sizeof(CLASS_UPPER) - 1; } else if (trio_equal_max(CLASS_XDIGIT, sizeof(CLASS_XDIGIT) - 1, &format[offset])) { for (i = 0; i < MAX_CHARACTER_CLASS; i++) if (isxdigit(i)) characterclass[i]++; offset += sizeof(CLASS_XDIGIT) - 1; } else { characterclass[(int)ch]++; } break; default: characterclass[(int)ch]++; break; } break; #endif /* TRIO_EXTENSION */ default: characterclass[(int)ch]++; break; } } return 0; } /************************************************************************* * TrioReadNumber * * We implement our own number conversion in preference of strtol and * strtoul, because we must handle 'long long' and thousand separators. */ TRIO_PRIVATE BOOLEAN_T TrioReadNumber TRIO_ARGS5((self, target, flags, width, base), trio_class_t* self, trio_uintmax_t* target, trio_flags_t flags, int width, int base) { trio_uintmax_t number = 0; int digit; int count; BOOLEAN_T isNegative = FALSE; BOOLEAN_T gotNumber = FALSE; int j; assert(VALID(self)); assert(VALID(self->InStream)); assert((base >= MIN_BASE && base <= MAX_BASE) || (base == NO_BASE)); if (internalDigitsUnconverted) { /* Lazy evaluation of digits array */ memset(internalDigitArray, -1, sizeof(internalDigitArray)); for (j = 0; j < (int)sizeof(internalDigitsLower) - 1; j++) { internalDigitArray[(int)internalDigitsLower[j]] = j; internalDigitArray[(int)internalDigitsUpper[j]] = j; } internalDigitsUnconverted = FALSE; } TrioSkipWhitespaces(self); /* Leading sign */ if (self->current == '+') { self->InStream(self, NULL); } else if (self->current == '-') { self->InStream(self, NULL); isNegative = TRUE; } count = self->processed; if (flags & FLAGS_ALTERNATIVE) { switch (base) { case NO_BASE: case BASE_OCTAL: case BASE_HEX: case BASE_BINARY: if (self->current == '0') { self->InStream(self, NULL); if (self->current) { if ((base == BASE_HEX) && (trio_to_upper(self->current) == 'X')) { self->InStream(self, NULL); } else if ((base == BASE_BINARY) && (trio_to_upper(self->current) == 'B')) { self->InStream(self, NULL); } } } else return FALSE; break; default: break; } } while (((width == NO_WIDTH) || (self->processed - count < width)) && (!((self->current == EOF) || isspace(self->current)))) { if (isascii(self->current)) { digit = internalDigitArray[self->current]; /* Abort if digit is not allowed in the specified base */ if ((digit == -1) || (digit >= base)) break; } #if TRIO_FEATURE_QUOTE else if (flags & FLAGS_QUOTE) { /* Compare with thousands separator */ for (j = 0; internalThousandSeparator[j] && self->current; j++) { if (internalThousandSeparator[j] != self->current) break; self->InStream(self, NULL); } if (internalThousandSeparator[j]) break; /* Mismatch */ else continue; /* Match */ } #endif else break; number *= base; number += digit; gotNumber = TRUE; /* we need at least one digit */ self->InStream(self, NULL); } /* Was anything read at all? */ if (!gotNumber) return FALSE; if (target) *target = (isNegative) ? (trio_uintmax_t)(-((trio_intmax_t)number)) : number; return TRUE; } /************************************************************************* * TrioReadChar */ TRIO_PRIVATE int TrioReadChar TRIO_ARGS4((self, target, flags, width), trio_class_t* self, char* target, trio_flags_t flags, int width) { int i; char ch; trio_uintmax_t number; assert(VALID(self)); assert(VALID(self->InStream)); for (i = 0; (self->current != EOF) && (i < width); i++) { ch = (char)self->current; self->InStream(self, NULL); if ((flags & FLAGS_ALTERNATIVE) && (ch == CHAR_BACKSLASH)) { switch (self->current) { case '\\': ch = '\\'; break; case 'a': ch = '\007'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case 'v': ch = '\v'; break; default: if (isdigit(self->current)) { /* Read octal number */ if (!TrioReadNumber(self, &number, 0, 3, BASE_OCTAL)) return 0; ch = (char)number; } else if (trio_to_upper(self->current) == 'X') { /* Read hexadecimal number */ self->InStream(self, NULL); if (!TrioReadNumber(self, &number, 0, 2, BASE_HEX)) return 0; ch = (char)number; } else { ch = (char)self->current; } break; } } if (target) target[i] = ch; } return i + 1; } /************************************************************************* * TrioReadString */ TRIO_PRIVATE BOOLEAN_T TrioReadString TRIO_ARGS4((self, target, flags, width), trio_class_t* self, char* target, trio_flags_t flags, int width) { int i; assert(VALID(self)); assert(VALID(self->InStream)); TrioSkipWhitespaces(self); /* * Continue until end of string is reached, a whitespace is encountered, * or width is exceeded */ for (i = 0; ((width == NO_WIDTH) || (i < width)) && (!((self->current == EOF) || isspace(self->current))); i++) { if (TrioReadChar(self, (target ? &target[i] : 0), flags, 1) == 0) break; /* for */ } if (target) target[i] = NIL; return TRUE; } /************************************************************************* * TrioReadWideChar */ #if TRIO_FEATURE_WIDECHAR TRIO_PRIVATE int TrioReadWideChar TRIO_ARGS4((self, target, flags, width), trio_class_t* self, trio_wchar_t* target, trio_flags_t flags, int width) { int i; int j; int size; int amount = 0; trio_wchar_t wch; char buffer[MB_LEN_MAX + 1]; assert(VALID(self)); assert(VALID(self->InStream)); for (i = 0; (self->current != EOF) && (i < width); i++) { if (isascii(self->current)) { if (TrioReadChar(self, buffer, flags, 1) == 0) return 0; buffer[1] = NIL; } else { /* * Collect a multibyte character, by enlarging buffer until * it contains a fully legal multibyte character, or the * buffer is full. */ j = 0; do { buffer[j++] = (char)self->current; buffer[j] = NIL; self->InStream(self, NULL); } while ((j < (int)sizeof(buffer)) && (mblen(buffer, (size_t)j) != j)); } if (target) { size = mbtowc(&wch, buffer, sizeof(buffer)); if (size > 0) target[i] = wch; } amount += size; self->InStream(self, NULL); } return amount; } #endif /* TRIO_FEATURE_WIDECHAR */ /************************************************************************* * TrioReadWideString */ #if TRIO_FEATURE_WIDECHAR TRIO_PRIVATE BOOLEAN_T TrioReadWideString TRIO_ARGS4((self, target, flags, width), trio_class_t* self, trio_wchar_t* target, trio_flags_t flags, int width) { int i; int size; assert(VALID(self)); assert(VALID(self->InStream)); TrioSkipWhitespaces(self); #if defined(TRIO_COMPILER_SUPPORTS_MULTIBYTE) /* Required by TrioReadWideChar */ (void)mblen(NULL, 0); #endif /* * Continue until end of string is reached, a whitespace is encountered, * or width is exceeded */ for (i = 0; ((width == NO_WIDTH) || (i < width)) && (!((self->current == EOF) || isspace(self->current)));) { size = TrioReadWideChar(self, &target[i], flags, 1); if (size == 0) break; /* for */ i += size; } if (target) target[i] = WCONST('\0'); return TRUE; } #endif /* TRIO_FEATURE_WIDECHAR */ /************************************************************************* * TrioReadGroup * * Reads non-empty character groups. * * FIXME: characterclass does not work with multibyte characters */ TRIO_PRIVATE BOOLEAN_T TrioReadGroup TRIO_ARGS5((self, target, characterclass, flags, width), trio_class_t* self, char* target, int* characterclass, trio_flags_t flags, int width) { int ch; int i; assert(VALID(self)); assert(VALID(self->InStream)); ch = self->current; for (i = 0; ((width == NO_WIDTH) || (i < width)) && (!((ch == EOF) || (((flags & FLAGS_EXCLUDE) != 0) ^ (characterclass[ch] == 0)))); i++) { if (target) target[i] = (char)ch; self->InStream(self, &ch); } if (i == 0) return FALSE; /* Terminate the string if input saved */ if (target) target[i] = NIL; return TRUE; } /************************************************************************* * TrioReadDouble * * FIXME: * add long double * handle base */ #if TRIO_FEATURE_FLOAT TRIO_PRIVATE BOOLEAN_T TrioReadDouble TRIO_ARGS4((self, target, flags, width), trio_class_t* self, trio_pointer_t target, trio_flags_t flags, int width) { int ch; char doubleString[512]; int offset = 0; int start; #if TRIO_FEATURE_QUOTE int j; #endif BOOLEAN_T isHex = FALSE; trio_long_double_t infinity; doubleString[0] = 0; if ((width == NO_WIDTH) || (width > (int)sizeof(doubleString) - 1)) width = sizeof(doubleString) - 1; TrioSkipWhitespaces(self); /* * Read entire double number from stream. trio_to_double requires * a string as input, but InStream can be anything, so we have to * collect all characters. */ ch = self->current; if ((ch == '+') || (ch == '-')) { doubleString[offset++] = (char)ch; self->InStream(self, &ch); width--; } start = offset; switch (ch) { case 'n': case 'N': /* Not-a-number */ if (offset != 0) break; /* FALLTHROUGH */ case 'i': case 'I': /* Infinity */ while (isalpha(ch) && (offset - start < width)) { doubleString[offset++] = (char)ch; self->InStream(self, &ch); } doubleString[offset] = NIL; /* Case insensitive string comparison */ if (trio_equal(&doubleString[start], INFINITE_UPPER) || trio_equal(&doubleString[start], LONG_INFINITE_UPPER)) { infinity = ((start == 1) && (doubleString[0] == '-')) ? trio_ninf() : trio_pinf(); if (!target) return FALSE; if (flags & FLAGS_LONGDOUBLE) { *((trio_long_double_t*)target) = infinity; } else if (flags & FLAGS_LONG) { *((double*)target) = infinity; } else { *((float*)target) = infinity; } return TRUE; } if (trio_equal(doubleString, NAN_UPPER)) { if (!target) return FALSE; /* NaN must not have a preceeding + nor - */ if (flags & FLAGS_LONGDOUBLE) { *((trio_long_double_t*)target) = trio_nan(); } else if (flags & FLAGS_LONG) { *((double*)target) = trio_nan(); } else { *((float*)target) = trio_nan(); } return TRUE; } return FALSE; case '0': doubleString[offset++] = (char)ch; self->InStream(self, &ch); if (trio_to_upper(ch) == 'X') { isHex = TRUE; doubleString[offset++] = (char)ch; self->InStream(self, &ch); } break; default: break; } while ((ch != EOF) && (offset - start < width)) { /* Integer part */ if (isHex ? isxdigit(ch) : isdigit(ch)) { doubleString[offset++] = (char)ch; self->InStream(self, &ch); } #if TRIO_FEATURE_QUOTE else if (flags & FLAGS_QUOTE) { /* Compare with thousands separator */ for (j = 0; internalThousandSeparator[j] && self->current; j++) { if (internalThousandSeparator[j] != self->current) break; self->InStream(self, &ch); } if (internalThousandSeparator[j]) break; /* Mismatch */ else continue; /* Match */ } #endif else break; /* while */ } if (ch == '.') { /* Decimal part */ doubleString[offset++] = (char)ch; self->InStream(self, &ch); while ((isHex ? isxdigit(ch) : isdigit(ch)) && (offset - start < width)) { doubleString[offset++] = (char)ch; self->InStream(self, &ch); } } if (isHex ? (trio_to_upper(ch) == 'P') : (trio_to_upper(ch) == 'E')) { /* Exponent */ doubleString[offset++] = (char)ch; self->InStream(self, &ch); if ((ch == '+') || (ch == '-')) { doubleString[offset++] = (char)ch; self->InStream(self, &ch); } while (isdigit(ch) && (offset - start < width)) { doubleString[offset++] = (char)ch; self->InStream(self, &ch); } } if ((offset == start) || (*doubleString == NIL)) return FALSE; doubleString[offset] = 0; if (flags & FLAGS_LONGDOUBLE) { if (!target) return FALSE; *((trio_long_double_t*)target) = trio_to_long_double(doubleString, NULL); } else if (flags & FLAGS_LONG) { if (!target) return FALSE; *((double*)target) = trio_to_double(doubleString, NULL); } else { if (!target) return FALSE; *((float*)target) = trio_to_float(doubleString, NULL); } return TRUE; } #endif /* TRIO_FEATURE_FLOAT */ /************************************************************************* * TrioReadPointer */ TRIO_PRIVATE BOOLEAN_T TrioReadPointer TRIO_ARGS3((self, target, flags), trio_class_t* self, trio_pointer_t* target, trio_flags_t flags) { trio_uintmax_t number; char buffer[sizeof(internalNullString)]; flags |= (FLAGS_UNSIGNED | FLAGS_ALTERNATIVE | FLAGS_NILPADDING); if (TrioReadNumber(self, &number, flags, POINTER_WIDTH, BASE_HEX)) { if (target) { #if defined(TRIO_COMPILER_GCC) || defined(TRIO_COMPILER_MIPSPRO) /* * The strange assignment of number is a workaround for a compiler * warning */ *target = &((char*)0)[number]; #else *target = (trio_pointer_t)number; #endif } return TRUE; } else if (TrioReadString(self, (flags & FLAGS_IGNORE) ? NULL : buffer, 0, sizeof(internalNullString) - 1)) { if (trio_equal_case(buffer, internalNullString)) { if (target) *target = NULL; return TRUE; } } return FALSE; } /************************************************************************* * TrioScanProcess */ TRIO_PRIVATE int TrioScanProcess TRIO_ARGS3((data, format, parameters), trio_class_t* data, TRIO_CONST char* format, trio_parameter_t* parameters) { int status; int assignment; int ch; int offset; /* Offset of format string */ int i; /* Offset of current parameter */ trio_flags_t flags; int width; int base; trio_pointer_t pointer; /* Return on empty format string */ if (format[0] == NIL) return 0; status = 0; assignment = 0; i = 0; offset = 0; data->InStream(data, &ch); for (;;) { /* Skip the parameter entries */ while (parameters[i].type == FORMAT_PARAMETER) { assert(i <= MAX_PARAMETERS); i++; } /* Compare non conversion-specifier part of format string */ while (offset < parameters[i].beginOffset) { if ((CHAR_IDENTIFIER == format[offset]) && (CHAR_IDENTIFIER == format[offset + 1])) { /* Two % in format matches one % in input stream */ if (CHAR_IDENTIFIER == ch) { data->InStream(data, &ch); offset += 2; continue; /* while format chars left */ } else { status = TRIO_ERROR_RETURN(TRIO_EINVAL, offset); goto end; } } else /* Not an % identifier */ { if (isspace((int)format[offset])) { /* Whitespaces may match any amount of whitespaces */ ch = TrioSkipWhitespaces(data); } else if (ch == format[offset]) { data->InStream(data, &ch); } else { status = assignment; goto end; } offset++; } } if (parameters[i].type == FORMAT_SENTINEL) break; if ((EOF == ch) && (parameters[i].type != FORMAT_COUNT)) { status = (assignment > 0) ? assignment : EOF; goto end; } flags = parameters[i].flags; /* Find width */ width = parameters[i].width; if (flags & FLAGS_WIDTH_PARAMETER) { /* Get width from parameter list */ width = (int)parameters[width].data.number.as_signed; } /* Find base */ if (NO_BASE != parameters[i].baseSpecifier) { /* Base from specifier has priority */ base = parameters[i].baseSpecifier; } else if (flags & FLAGS_BASE_PARAMETER) { /* Get base from parameter list */ base = parameters[i].base; base = (int)parameters[base].data.number.as_signed; } else { /* Use base from format string */ base = parameters[i].base; } switch (parameters[i].type) { case FORMAT_INT: { trio_uintmax_t number; if (0 == base) base = BASE_DECIMAL; if (!TrioReadNumber(data, &number, flags, width, base)) { status = assignment; goto end; } if (!(flags & FLAGS_IGNORE)) { assignment++; pointer = parameters[i].data.pointer; #if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER if (flags & FLAGS_SIZE_T) *(size_t*)pointer = (size_t)number; else #endif #if TRIO_FEATURE_PTRDIFF_T if (flags & FLAGS_PTRDIFF_T) *(ptrdiff_t*)pointer = (ptrdiff_t)number; else #endif #if TRIO_FEATURE_INTMAX_T if (flags & FLAGS_INTMAX_T) *(trio_intmax_t*)pointer = (trio_intmax_t)number; else #endif if (flags & FLAGS_QUAD) *(trio_ulonglong_t*)pointer = (trio_ulonglong_t)number; else if (flags & FLAGS_LONG) *(long int*)pointer = (long int)number; else if (flags & FLAGS_SHORT) *(short int*)pointer = (short int)number; else *(int*)pointer = (int)number; } } break; /* FORMAT_INT */ case FORMAT_STRING: #if TRIO_FEATURE_WIDECHAR if (flags & FLAGS_WIDECHAR) { if (!TrioReadWideString( data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.wstring, flags, width)) { status = assignment; goto end; } } else #endif { if (!TrioReadString(data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.string, flags, width)) { status = assignment; goto end; } } if (!(flags & FLAGS_IGNORE)) assignment++; break; /* FORMAT_STRING */ #if TRIO_FEATURE_FLOAT case FORMAT_DOUBLE: { if (flags & FLAGS_IGNORE) { pointer = NULL; } else { pointer = (flags & FLAGS_LONGDOUBLE) ? (trio_pointer_t)parameters[i].data.longdoublePointer : (trio_pointer_t)parameters[i].data.doublePointer; } if (!TrioReadDouble(data, pointer, flags, width)) { status = assignment; goto end; } if (!(flags & FLAGS_IGNORE)) { assignment++; } break; /* FORMAT_DOUBLE */ } #endif case FORMAT_GROUP: { int characterclass[MAX_CHARACTER_CLASS + 1]; /* Skip over modifiers */ while (format[offset] != SPECIFIER_GROUP) { offset++; } /* Skip over group specifier */ offset++; memset(characterclass, 0, sizeof(characterclass)); status = TrioGetCharacterClass(format, &offset, &flags, characterclass); if (status < 0) goto end; if (!TrioReadGroup(data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.string, characterclass, flags, parameters[i].width)) { status = assignment; goto end; } if (!(flags & FLAGS_IGNORE)) assignment++; } break; /* FORMAT_GROUP */ case FORMAT_COUNT: pointer = parameters[i].data.pointer; if (NULL != pointer) { int count = data->processed; if (ch != EOF) count--; /* a character is read, but is not consumed yet */ #if TRIO_FEATURE_SIZE_T || TRIO_FEATURE_SIZE_T_UPPER if (flags & FLAGS_SIZE_T) *(size_t*)pointer = (size_t)count; else #endif #if TRIO_FEATURE_PTRDIFF_T if (flags & FLAGS_PTRDIFF_T) *(ptrdiff_t*)pointer = (ptrdiff_t)count; else #endif #if TRIO_FEATURE_INTMAX_T if (flags & FLAGS_INTMAX_T) *(trio_intmax_t*)pointer = (trio_intmax_t)count; else #endif if (flags & FLAGS_QUAD) { *(trio_ulonglong_t*)pointer = (trio_ulonglong_t)count; } else if (flags & FLAGS_LONG) { *(long int*)pointer = (long int)count; } else if (flags & FLAGS_SHORT) { *(short int*)pointer = (short int)count; } else { *(int*)pointer = (int)count; } } break; /* FORMAT_COUNT */ case FORMAT_CHAR: #if TRIO_FEATURE_WIDECHAR if (flags & FLAGS_WIDECHAR) { if (TrioReadWideChar(data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.wstring, flags, (width == NO_WIDTH) ? 1 : width) == 0) { status = assignment; goto end; } } else #endif { if (TrioReadChar(data, (flags & FLAGS_IGNORE) ? NULL : parameters[i].data.string, flags, (width == NO_WIDTH) ? 1 : width) == 0) { status = assignment; goto end; } } if (!(flags & FLAGS_IGNORE)) assignment++; break; /* FORMAT_CHAR */ case FORMAT_POINTER: if (!TrioReadPointer( data, (flags & FLAGS_IGNORE) ? NULL : (trio_pointer_t*)parameters[i].data.pointer, flags)) { status = assignment; goto end; } if (!(flags & FLAGS_IGNORE)) assignment++; break; /* FORMAT_POINTER */ case FORMAT_PARAMETER: break; /* FORMAT_PARAMETER */ default: status = TRIO_ERROR_RETURN(TRIO_EINVAL, offset); goto end; } ch = data->current; offset = parameters[i].endOffset; i++; } status = assignment; end: if (data->UndoStream) data->UndoStream(data); return status; } /************************************************************************* * TrioScan */ TRIO_PRIVATE int TrioScan TRIO_ARGS8( (source, sourceSize, InStream, UndoStream, format, arglist, argfunc, argarray), trio_pointer_t source, size_t sourceSize, void(*InStream) TRIO_PROTO((trio_class_t*, int*)), void(*UndoStream) TRIO_PROTO((trio_class_t*)), TRIO_CONST char* format, va_list arglist, trio_argfunc_t argfunc, trio_pointer_t* argarray) { int status; trio_parameter_t parameters[MAX_PARAMETERS]; trio_class_t data; assert(VALID(InStream)); assert(VALID(format)); memset(&data, 0, sizeof(data)); data.InStream = InStream; data.UndoStream = UndoStream; data.location = (trio_pointer_t)source; data.max = sourceSize; data.error = 0; #if defined(USE_LOCALE) if (NULL == internalLocaleValues) { TrioSetLocale(); } #endif status = TrioParse(TYPE_SCAN, format, parameters, arglist, argfunc, argarray); if (status < 0) return status; status = TrioScanProcess(&data, format, parameters); if (data.error != 0) { status = data.error; } return status; } /************************************************************************* * TrioInStreamFile */ #if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO TRIO_PRIVATE void TrioInStreamFile TRIO_ARGS2((self, intPointer), trio_class_t* self, int* intPointer) { FILE* file = (FILE*)self->location; assert(VALID(self)); assert(VALID(file)); self->actually.cached = 0; /* The initial value of self->current is zero */ if (self->current == EOF) { self->error = (ferror(file)) ? TRIO_ERROR_RETURN(TRIO_ERRNO, 0) : TRIO_ERROR_RETURN(TRIO_EOF, 0); } else { self->processed++; self->actually.cached++; } self->current = fgetc(file); if (VALID(intPointer)) { *intPointer = self->current; } } #endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */ /************************************************************************* * TrioUndoStreamFile */ #if TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO TRIO_PRIVATE void TrioUndoStreamFile TRIO_ARGS1((self), trio_class_t* self) { FILE* file = (FILE*)self->location; assert(VALID(self)); assert(VALID(file)); if (self->actually.cached > 0) { assert(self->actually.cached == 1); self->current = ungetc(self->current, file); self->actually.cached = 0; } } #endif /* TRIO_FEATURE_FILE || TRIO_FEATURE_STDIO */ /************************************************************************* * TrioInStreamFileDescriptor */ #if TRIO_FEATURE_FD TRIO_PRIVATE void TrioInStreamFileDescriptor TRIO_ARGS2((self, intPointer), trio_class_t* self, int* intPointer) { int fd = *((int*)self->location); int size; unsigned char input; assert(VALID(self)); self->actually.cached = 0; size = read(fd, &input, sizeof(char)); if (size == -1) { self->error = TRIO_ERROR_RETURN(TRIO_ERRNO, 0); self->current = EOF; } else { self->current = (size == 0) ? EOF : input; } if (self->current != EOF) { self->actually.cached++; self->processed++; } if (VALID(intPointer)) { *intPointer = self->current; } } #endif /* TRIO_FEATURE_FD */ /************************************************************************* * TrioInStreamCustom */ #if TRIO_FEATURE_CLOSURE TRIO_PRIVATE void TrioInStreamCustom TRIO_ARGS2((self, intPointer), trio_class_t* self, int* intPointer) { trio_custom_t* data; assert(VALID(self)); assert(VALID(self->location)); self->actually.cached = 0; data = (trio_custom_t*)self->location; self->current = (data->stream.in == NULL) ? NIL : (data->stream.in)(data->closure); if (self->current == NIL) { self->current = EOF; } else { self->processed++; self->actually.cached++; } if (VALID(intPointer)) { *intPointer = self->current; } } #endif /* TRIO_FEATURE_CLOSURE */ /************************************************************************* * TrioInStreamString */ TRIO_PRIVATE void TrioInStreamString TRIO_ARGS2((self, intPointer), trio_class_t* self, int* intPointer) { unsigned char** buffer; assert(VALID(self)); assert(VALID(self->location)); self->actually.cached = 0; buffer = (unsigned char**)self->location; self->current = (*buffer)[0]; if (self->current == NIL) { self->current = EOF; } else { (*buffer)++; self->processed++; self->actually.cached++; } if (VALID(intPointer)) { *intPointer = self->current; } } /************************************************************************* * * Formatted scanning functions * ************************************************************************/ #if defined(TRIO_DOCUMENTATION) #include "doc/doc_scanf.h" #endif /** @addtogroup Scanf @{ */ /************************************************************************* * scanf */ /** Scan characters from standard input stream. @param format Formatting string. @param ... Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_STDIO TRIO_PUBLIC int trio_scanf TRIO_VARGS2((format, va_alist), TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(format)); TRIO_VA_START(args, format); status = TrioScan((trio_pointer_t)stdin, 0, TrioInStreamFile, TrioUndoStreamFile, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_STDIO */ /** Scan characters from standard input stream. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_STDIO TRIO_PUBLIC int trio_vscanf TRIO_ARGS2((format, args), TRIO_CONST char* format, va_list args) { assert(VALID(format)); return TrioScan((trio_pointer_t)stdin, 0, TrioInStreamFile, TrioUndoStreamFile, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_STDIO */ /** Scan characters from standard input stream. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_STDIO TRIO_PUBLIC int trio_scanfv TRIO_ARGS2((format, args), TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(format)); return TrioScan((trio_pointer_t)stdin, 0, TrioInStreamFile, TrioUndoStreamFile, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_STDIO */ /************************************************************************* * fscanf */ /** Scan characters from file. @param file File pointer. @param format Formatting string. @param ... Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_FILE TRIO_PUBLIC int trio_fscanf TRIO_VARGS3((file, format, va_alist), FILE* file, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(file)); assert(VALID(format)); TRIO_VA_START(args, format); status = TrioScan((trio_pointer_t)file, 0, TrioInStreamFile, TrioUndoStreamFile, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_FILE */ /** Scan characters from file. @param file File pointer. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_FILE TRIO_PUBLIC int trio_vfscanf TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format, va_list args) { assert(VALID(file)); assert(VALID(format)); return TrioScan((trio_pointer_t)file, 0, TrioInStreamFile, TrioUndoStreamFile, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_FILE */ /** Scan characters from file. @param file File pointer. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_FILE TRIO_PUBLIC int trio_fscanfv TRIO_ARGS3((file, format, args), FILE* file, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(file)); assert(VALID(format)); return TrioScan((trio_pointer_t)file, 0, TrioInStreamFile, TrioUndoStreamFile, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_FILE */ /************************************************************************* * dscanf */ /** Scan characters from file descriptor. @param fd File descriptor. @param format Formatting string. @param ... Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_FD TRIO_PUBLIC int trio_dscanf TRIO_VARGS3((fd, format, va_alist), int fd, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(format)); TRIO_VA_START(args, format); status = TrioScan((trio_pointer_t)&fd, 0, TrioInStreamFileDescriptor, NULL, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_FD */ /** Scan characters from file descriptor. @param fd File descriptor. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_FD TRIO_PUBLIC int trio_vdscanf TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format, va_list args) { assert(VALID(format)); return TrioScan((trio_pointer_t)&fd, 0, TrioInStreamFileDescriptor, NULL, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_FD */ /** Scan characters from file descriptor. @param fd File descriptor. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ #if TRIO_FEATURE_FD TRIO_PUBLIC int trio_dscanfv TRIO_ARGS3((fd, format, args), int fd, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(format)); return TrioScan((trio_pointer_t)&fd, 0, TrioInStreamFileDescriptor, NULL, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_FD */ /************************************************************************* * cscanf */ #if TRIO_FEATURE_CLOSURE TRIO_PUBLIC int trio_cscanf TRIO_VARGS4((stream, closure, format, va_alist), trio_instream_t stream, trio_pointer_t closure, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); TRIO_VA_START(args, format); data.stream.in = stream; data.closure = closure; status = TrioScan(&data, 0, TrioInStreamCustom, NULL, format, args, NULL, NULL); TRIO_VA_END(args); return status; } #endif /* TRIO_FEATURE_CLOSURE */ #if TRIO_FEATURE_CLOSURE TRIO_PUBLIC int trio_vcscanf TRIO_ARGS4((stream, closure, format, args), trio_instream_t stream, trio_pointer_t closure, TRIO_CONST char* format, va_list args) { trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); data.stream.in = stream; data.closure = closure; return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, args, NULL, NULL); } #endif /* TRIO_FEATURE_CLOSURE */ #if TRIO_FEATURE_CLOSURE TRIO_PUBLIC int trio_cscanfv TRIO_ARGS4((stream, closure, format, args), trio_instream_t stream, trio_pointer_t closure, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); data.stream.in = stream; data.closure = closure; return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_CLOSURE */ #if TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC TRIO_PUBLIC int trio_cscanff TRIO_ARGS5((stream, closure, format, argfunc, context), trio_instream_t stream, trio_pointer_t closure, TRIO_CONST char* format, trio_argfunc_t argfunc, trio_pointer_t context) { static va_list unused; trio_custom_t data; assert(VALID(stream)); assert(VALID(format)); assert(VALID(argfunc)); data.stream.in = stream; data.closure = closure; return TrioScan(&data, 0, TrioInStreamCustom, NULL, format, unused, argfunc, (trio_pointer_t*)context); } #endif /* TRIO_FEATURE_CLOSURE && TRIO_FEATURE_ARGFUNC */ /************************************************************************* * sscanf */ /** Scan characters from string. @param buffer Input string. @param format Formatting string. @param ... Arguments. @return Number of scanned characters. */ TRIO_PUBLIC int trio_sscanf TRIO_VARGS3((buffer, format, va_alist), TRIO_CONST char* buffer, TRIO_CONST char* format, TRIO_VA_DECL) { int status; va_list args; assert(VALID(buffer)); assert(VALID(format)); TRIO_VA_START(args, format); status = TrioScan((trio_pointer_t)&buffer, 0, TrioInStreamString, NULL, format, args, NULL, NULL); TRIO_VA_END(args); return status; } /** Scan characters from string. @param buffer Input string. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ TRIO_PUBLIC int trio_vsscanf TRIO_ARGS3((buffer, format, args), TRIO_CONST char* buffer, TRIO_CONST char* format, va_list args) { assert(VALID(buffer)); assert(VALID(format)); return TrioScan((trio_pointer_t)&buffer, 0, TrioInStreamString, NULL, format, args, NULL, NULL); } /** Scan characters from string. @param buffer Input string. @param format Formatting string. @param args Arguments. @return Number of scanned characters. */ TRIO_PUBLIC int trio_sscanfv TRIO_ARGS3((buffer, format, args), TRIO_CONST char* buffer, TRIO_CONST char* format, trio_pointer_t* args) { static va_list unused; assert(VALID(buffer)); assert(VALID(format)); return TrioScan((trio_pointer_t)&buffer, 0, TrioInStreamString, NULL, format, unused, TrioArrayGetter, args); } #endif /* TRIO_FEATURE_SCANF */ /** @} End of Scanf documentation module */ /************************************************************************* * trio_strerror */ TRIO_PUBLIC TRIO_CONST char* trio_strerror TRIO_ARGS1((errorcode), int errorcode) { #if TRIO_FEATURE_STRERR /* Textual versions of the error codes */ switch (TRIO_ERROR_CODE(errorcode)) { case TRIO_EOF: return "End of file"; case TRIO_EINVAL: return "Invalid argument"; case TRIO_ETOOMANY: return "Too many arguments"; case TRIO_EDBLREF: return "Double reference"; case TRIO_EGAP: return "Reference gap"; case TRIO_ENOMEM: return "Out of memory"; case TRIO_ERANGE: return "Invalid range"; case TRIO_ECUSTOM: return "Custom error"; default: return "Unknown"; } #else return "Unknown"; #endif } #ifdef _WIN32 #pragma warning(pop) #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_4493_0
crossvul-cpp_data_good_3358_3
/* * IPV6 GSO/GRO offload support * Linux INET6 implementation * * 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. * * UDPv6 GSO support */ #include <linux/skbuff.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <net/ipv6.h> #include <net/udp.h> #include <net/ip6_checksum.h> #include "ip6_offload.h" static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; unsigned int unfrag_ip6hlen, unfrag_len; struct frag_hdr *fptr; u8 *packet_start, *prevhdr; u8 nexthdr; u8 frag_hdr_sz = sizeof(struct frag_hdr); __wsum csum; int tnl_hlen; mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); /* Set the IPv6 fragment id if not set yet */ if (!skb_shinfo(skb)->ip6_frag_id) ipv6_proxy_select_ident(dev_net(skb->dev), skb); segs = NULL; goto out; } if (skb->encapsulation && skb_shinfo(skb)->gso_type & (SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM)) segs = skb_udp_tunnel_segment(skb, features, true); else { const struct ipv6hdr *ipv6h; struct udphdr *uh; if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto out; /* Do software UFO. Complete and fill in the UDP checksum as HW cannot * do checksum of UDP packets sent as multiple IP fragments. */ uh = udp_hdr(skb); ipv6h = ipv6_hdr(skb); uh->check = 0; csum = skb_checksum(skb, 0, skb->len, 0); uh->check = udp_v6_check(skb->len, &ipv6h->saddr, &ipv6h->daddr, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; skb->ip_summed = CHECKSUM_NONE; /* If there is no outer header we can fake a checksum offload * due to the fact that we have already done the checksum in * software prior to segmenting the frame. */ if (!skb->encap_hdr_csum) features |= NETIF_F_HW_CSUM; /* Check if there is enough headroom to insert fragment header. */ tnl_hlen = skb_tnl_header_len(skb); if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) { if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz)) goto out; } /* Find the unfragmentable header and shift it left by frag_hdr_sz * bytes to insert fragment header. */ unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); if (unfrag_ip6hlen < 0) return ERR_PTR(unfrag_ip6hlen); nexthdr = *prevhdr; *prevhdr = NEXTHDR_FRAGMENT; unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) + unfrag_ip6hlen + tnl_hlen; packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset; memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len); SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz; skb->mac_header -= frag_hdr_sz; skb->network_header -= frag_hdr_sz; fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen); fptr->nexthdr = nexthdr; fptr->reserved = 0; if (!skb_shinfo(skb)->ip6_frag_id) ipv6_proxy_select_ident(dev_net(skb->dev), skb); fptr->identification = skb_shinfo(skb)->ip6_frag_id; /* Fragment the skb. ipv6 header and the remaining fields of the * fragment header are updated in ipv6_gso_segment() */ segs = skb_segment(skb, features); } out: return segs; } static struct sk_buff **udp6_gro_receive(struct sk_buff **head, struct sk_buff *skb) { struct udphdr *uh = udp_gro_udphdr(skb); if (unlikely(!uh)) goto flush; /* Don't bother verifying checksum if we're going to flush anyway. */ if (NAPI_GRO_CB(skb)->flush) goto skip; if (skb_gro_checksum_validate_zero_check(skb, IPPROTO_UDP, uh->check, ip6_gro_compute_pseudo)) goto flush; else if (uh->check) skb_gro_checksum_try_convert(skb, IPPROTO_UDP, uh->check, ip6_gro_compute_pseudo); skip: NAPI_GRO_CB(skb)->is_ipv6 = 1; return udp_gro_receive(head, skb, uh, udp6_lib_lookup_skb); flush: NAPI_GRO_CB(skb)->flush = 1; return NULL; } static int udp6_gro_complete(struct sk_buff *skb, int nhoff) { const struct ipv6hdr *ipv6h = ipv6_hdr(skb); struct udphdr *uh = (struct udphdr *)(skb->data + nhoff); if (uh->check) { skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL_CSUM; uh->check = ~udp_v6_check(skb->len - nhoff, &ipv6h->saddr, &ipv6h->daddr, 0); } else { skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL; } return udp_gro_complete(skb, nhoff, udp6_lib_lookup_skb); } static const struct net_offload udpv6_offload = { .callbacks = { .gso_segment = udp6_ufo_fragment, .gro_receive = udp6_gro_receive, .gro_complete = udp6_gro_complete, }, }; int udpv6_offload_init(void) { return inet6_add_offload(&udpv6_offload, IPPROTO_UDP); } int udpv6_offload_exit(void) { return inet6_del_offload(&udpv6_offload, IPPROTO_UDP); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3358_3
crossvul-cpp_data_bad_1297_0
/* * card-setcos.c: Support for PKI cards by Setec * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005 Antti Tapaninen <aet@cc.hut.fi> * Copyright (C) 2005 Zetes * * 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 "asn1.h" #include "cardctl.h" #define _FINEID_BROKEN_SELECT_FLAG 1 static const struct sc_atr_table setcos_atrs[] = { /* some Nokia branded SC */ { "3B:1F:11:00:67:80:42:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_GENERIC, 0, NULL }, /* RSA SecurID 3100 */ { "3B:9F:94:40:1E:00:67:16:43:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_PKI, 0, NULL }, /* FINEID 1016 (SetCOS 4.3.1B3/PKCS#15, VRK) */ { "3b:9f:94:40:1e:00:67:00:43:46:49:53:45:10:52:66:ff:81:90:00", "ff:ff:ff:ff:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID, SC_CARD_FLAG_RNG, NULL }, /* FINEID 2032 (EIDApplet/7816-15, VRK test) */ { "3b:6b:00:ff:80:62:00:a2:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2132 (EIDApplet/7816-15, 3rdparty test) */ { "3b:64:00:ff:80:62:00:a2", "ff:ff:00:ff:ff:ff:00:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2064 (EIDApplet/7816-15, VRK) */ { "3b:7b:00:00:00:80:62:00:51:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:ff:f0:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2164 (EIDApplet/7816-15, 3rdparty) */ { "3b:64:00:00:80:62:00:51", "ff:ff:ff:ff:ff:ff:f0:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2264 (EIDApplet/7816-15, OPK/EMV/AVANT) */ { "3b:6e:00:00:00:62:00:00:57:41:56:41:4e:54:10:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, { "3b:7b:94:00:00:80:62:11:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID cards 1.3.2011 with Samsung chips (round connector) that supports 2048 bit keys. */ { "3b:7b:94:00:00:80:62:12:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2_2048, 0, NULL }, /* FINEID card for organisations, chip unknown. */ { "3b:7b:18:00:00:80:62:01:54:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, _FINEID_BROKEN_SELECT_FLAG, NULL }, /* Swedish NIDEL card */ { "3b:9f:94:80:1f:c3:00:68:10:44:05:01:46:49:53:45:31:c8:07:90:00:18", NULL, NULL, SC_CARD_TYPE_SETCOS_NIDEL, 0, NULL }, /* Setcos 4.4.1 */ { "3b:9f:94:80:1f:c3:00:68:11:44:05:01:46:49:53:45:31:c8:00:00:00:00", "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:00:00:00:00", NULL, SC_CARD_TYPE_SETCOS_44, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define SETCOS_IS_EID_APPLET(card) ((card)->type == SC_CARD_TYPE_SETCOS_EID_V2_0 || (card)->type == SC_CARD_TYPE_SETCOS_EID_V2_1) /* Setcos 4.4 Life Cycle Status Integer */ #define SETEC_LCSI_CREATE 0x01 #define SETEC_LCSI_INIT 0x03 #define SETEC_LCSI_ACTIVATED 0x07 #define SETEC_LCSI_DEACTIVATE 0x06 #define SETEC_LCSI_TEMINATE 0x0F /* MF only */ static struct sc_card_operations setcos_ops; static struct sc_card_driver setcos_drv = { "Setec cards", "setcos", &setcos_ops, NULL, 0, NULL }; static int match_hist_bytes(sc_card_t *card, const char *str, size_t len) { const char *src = (const char *) card->reader->atr_info.hist_bytes; size_t srclen = card->reader->atr_info.hist_bytes_len; size_t offset = 0; if (len == 0) len = strlen(str); if (srclen < len) return 0; while (srclen - offset > len) { if (memcmp(src + offset, str, len) == 0) { return 1; } offset++; } return 0; } static int setcos_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 buf[6]; int i; i = _sc_match_atr(card, setcos_atrs, &card->type); if (i < 0) { /* Unknown card, but has the FinEID application for sure */ if (match_hist_bytes(card, "FinEID", 0)) { card->type = SC_CARD_TYPE_SETCOS_FINEID_V2_2048; return 1; } if (match_hist_bytes(card, "FISE", 0)) { card->type = SC_CARD_TYPE_SETCOS_GENERIC; return 1; } /* Check if it's a EID2.x applet by reading the version info */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0xDF, 0x30); apdu.cla = 0x00; apdu.resp = buf; apdu.resplen = 5; apdu.le = 5; i = sc_transmit_apdu(card, &apdu); if (i == 0 && apdu.sw1 == 0x90 && apdu.sw2 == 0x00 && apdu.resplen == 5) { if (memcmp(buf, "v2.0", 4) == 0) card->type = SC_CARD_TYPE_SETCOS_EID_V2_0; else if (memcmp(buf, "v2.1", 4) == 0) card->type = SC_CARD_TYPE_SETCOS_EID_V2_1; else { buf[sizeof(buf) - 1] = '\0'; sc_log(card->ctx, "SetCOS EID applet %s is not supported", (char *) buf); return 0; } return 1; } return 0; } card->flags = setcos_atrs[i].flags; return 1; } static int select_pkcs15_app(sc_card_t * card) { sc_path_t app; int r; /* Regular PKCS#15 AID */ sc_format_path("A000000063504B43532D3135", &app); app.type = SC_PATH_TYPE_DF_NAME; r = sc_select_file(card, &app, NULL); return r; } static int setcos_init(sc_card_t *card) { card->name = "SetCOS"; /* Handle unknown or forced cards */ if (card->type < 0) { card->type = SC_CARD_TYPE_SETCOS_GENERIC; } switch (card->type) { case SC_CARD_TYPE_SETCOS_FINEID: case SC_CARD_TYPE_SETCOS_FINEID_V2_2048: case SC_CARD_TYPE_SETCOS_NIDEL: card->cla = 0x00; select_pkcs15_app(card); if (card->flags & SC_CARD_FLAG_RNG) card->caps |= SC_CARD_CAP_RNG; break; case SC_CARD_TYPE_SETCOS_44: case SC_CARD_TYPE_SETCOS_EID_V2_0: case SC_CARD_TYPE_SETCOS_EID_V2_1: card->cla = 0x00; card->caps |= SC_CARD_CAP_USE_FCI_AC; card->caps |= SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; break; default: /* XXX: Get SetCOS version */ card->cla = 0x80; /* SetCOS 4.3.x */ /* State that we have an RNG */ card->caps |= SC_CARD_CAP_RNG; break; } switch (card->type) { case SC_CARD_TYPE_SETCOS_PKI: case SC_CARD_TYPE_SETCOS_FINEID_V2_2048: { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } break; case SC_CARD_TYPE_SETCOS_44: case SC_CARD_TYPE_SETCOS_NIDEL: case SC_CARD_TYPE_SETCOS_EID_V2_0: case SC_CARD_TYPE_SETCOS_EID_V2_1: { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _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); } break; } return 0; } static const struct sc_card_operations *iso_ops = NULL; static int setcos_construct_fci_44(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; const u8 *pin_key_info; int len; /* Command */ *p++ = 0x6F; p++; /* Size (set to 0 for keys/PINs on a Java card) */ if (SETCOS_IS_EID_APPLET(card) && (file->type == SC_FILE_TYPE_INTERNAL_EF || (file->type == SC_FILE_TYPE_WORKING_EF && file->ef_structure == 0x22))) buf[0] = buf[1] = 0x00; else { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; } sc_asn1_put_tag(0x81, buf, 2, p, *outlen - (p - out), &p); /* Type */ if (file->type_attr_len) { memcpy(buf, file->type_attr, file->type_attr_len); sc_asn1_put_tag(0x82, buf, file->type_attr_len, p, *outlen - (p - out), &p); } else { u8 bLen = 1; buf[0] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_INTERNAL_EF: /* RSA keyfile */ buf[0] = 0x11; break; case SC_FILE_TYPE_WORKING_EF: if (file->ef_structure == 0x22) { /* pin-file */ buf[0] = 0x0A; /* EF linear fixed EF for ISF keys */ if (SETCOS_IS_EID_APPLET(card)) bLen = 1; else { /* Setcos V4.4 */ bLen = 5; buf[1] = 0x41; /* fixed */ buf[2] = file->record_length >> 8; /* 2 byte record length */ buf[3] = file->record_length & 0xFF; buf[4] = file->size / file->record_length; /* record count */ } } else { buf[0] |= file->ef_structure & 7; /* set file-type, only for EF, not for DF objects */ } break; case SC_FILE_TYPE_DF: buf[0] = 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, bLen, p, *outlen - (p - out), &p); } /* File ID */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); /* DF name */ if (file->type == SC_FILE_TYPE_DF) { if (file->name[0] != 0) sc_asn1_put_tag(0x84, (u8 *) file->name, file->namelen, p, *outlen - (p - out), &p); else { /* Name required -> take the FID if not specified */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x84, buf, 2, p, *outlen - (p - out), &p); } } /* Security Attributes */ memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); /* Life cycle status */ if (file->prop_attr_len) { memcpy(buf, file->prop_attr, file->prop_attr_len); sc_asn1_put_tag(0x8A, buf, file->prop_attr_len, p, *outlen - (p - out), &p); } /* PIN definitions */ if (file->type == SC_FILE_TYPE_DF) { if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_1) { pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84"; len = 6; } else if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_0) { pin_key_info = (const u8*)"\xC1\x04\x81\x82"; /* Max 2 PINs supported */ len = 4; } else { /* Pin/key info: define 4 pins, no keys */ if(file->path.len == 2) pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84\xC2\x00"; /* root-MF: use local pin-file */ else pin_key_info = (const u8 *)"\xC1\x04\x01\x02\x03\x04\xC2\x00"; /* sub-DF: use parent pin-file in root-MF */ len = 8; } sc_asn1_put_tag(0xA5, pin_key_info, len, p, *outlen - (p - out), &p); } /* Length */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int setcos_construct_fci(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen) { if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) return setcos_construct_fci_44(card, file, out, outlen); else return iso_ops->construct_fci(card, file, out, outlen); } static u8 acl_to_byte(const sc_acl_entry_t *e) { switch (e->method) { case SC_AC_NONE: return 0x00; case SC_AC_CHV: switch (e->key_ref) { case 1: return 0x01; break; case 2: return 0x02; break; default: return 0x00; } break; case SC_AC_TERM: return 0x04; case SC_AC_NEVER: return 0x0F; } return 0x00; } static unsigned int acl_to_byte_44(const struct sc_acl_entry *e, u8* p_bNumber) { /* Handle special fixed values */ if (e == (sc_acl_entry_t *) 1) /* SC_AC_NEVER */ return SC_AC_NEVER; else if ((e == (sc_acl_entry_t *) 2) || /* SC_AC_NONE */ (e == (sc_acl_entry_t *) 3) || /* SC_AC_UNKNOWN */ (e == (sc_acl_entry_t *) 0)) return SC_AC_NONE; /* Handle standard values */ *p_bNumber = e->key_ref; return(e->method); } /* If pin is present in the pins list, return it's index. * If it's not yet present, add it to the list and return the index. */ static int setcos_pin_index_44(int *pins, int len, int pin) { int i; for (i = 0; i < len; i++) { if (pins[i] == pin) return i; if (pins[i] == -1) { pins[i] = pin; return i; } } assert(i != len); /* Too much PINs, shouldn't happen */ return 0; } /* The ACs are always for the SETEC_LCSI_ACTIVATED state, even if * we have to create the file in the SC_FILE_STATUS_INITIALISATION state. */ static int setcos_create_file_44(sc_card_t *card, sc_file_t *file) { const u8 bFileStatus = file->status == SC_FILE_STATUS_CREATION ? SETEC_LCSI_CREATE : SETEC_LCSI_ACTIVATED; u8 bCommands_always = 0; int pins[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; u8 bCommands_pin[sizeof(pins)/sizeof(pins[0])]; /* both 7 entries big */ u8 bCommands_key = 0; u8 bNumber = 0; u8 bKeyNumber = 0; unsigned int bMethod = 0; /* -1 means RFU */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { /* note: SC_AC_OP_SELECT to be ignored, actually RFU */ SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; /* Set file creation status */ sc_file_set_prop_attr(file, &bFileStatus, 1); /* Build ACI from local structure = get AC for each operation group */ if (file->sec_attr_len == 0) { const int* p_idx; int i; int len = 0; u8 bBuf[64]; /* Get specific operation groups for specified file-type */ switch (file->type){ case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* SC_FILE_TYPE_WORKING_EF */ p_idx = ef_idx; break; } /* Get enabled commands + required Keys/Pins */ memset(bCommands_pin, 0, sizeof(bCommands_pin)); for (i = 7; i >= 0; i--) { /* for each AC Setcos operation */ bCommands_always <<= 1; bCommands_key <<= 1; if (p_idx[i] == -1) /* -1 means that bit is RFU -> set to 0 */ continue; bMethod = acl_to_byte_44(file->acl[ p_idx[i] ], &bNumber); /* Convert to OpenSc-index, convert to pin/key number */ switch(bMethod){ case SC_AC_NONE: /* always allowed */ bCommands_always |= 1; break; case SC_AC_CHV: /* pin */ if ((bNumber & 0x7F) == 0 || (bNumber & 0x7F) > 7) { sc_log(card->ctx, "SetCOS 4.4 PIN refs can only be 1..7\n"); return SC_ERROR_INVALID_ARGUMENTS; } bCommands_pin[setcos_pin_index_44(pins, sizeof(pins), (int) bNumber)] |= 1 << i; break; case SC_AC_TERM: /* key */ bKeyNumber = bNumber; /* There should be only 1 key */ bCommands_key |= 1; break; } } /* Add the commands that are always allowed */ if (bCommands_always) { bBuf[len++] = 1; bBuf[len++] = bCommands_always; } /* Add commands that require pins */ for (i = 0; i < (int)sizeof(bCommands_pin) && pins[i] != -1; i++) { bBuf[len++] = 2; bBuf[len++] = bCommands_pin[i]; if (SETCOS_IS_EID_APPLET(card)) bBuf[len++] = pins[i]; /* pin ref */ else bBuf[len++] = pins[i] & 0x07; /* pin ref */ } /* Add commands that require the key */ if (bCommands_key) { bBuf[len++] = 2 | 0x20; /* indicate keyNumber present */ bBuf[len++] = bCommands_key; bBuf[len++] = bKeyNumber; } /* RSA signing/decryption requires AC adaptive coding, can't be put in AC simple coding. Only implemented for pins, not for a key. */ if ( (file->type == SC_FILE_TYPE_INTERNAL_EF) && (acl_to_byte_44(file->acl[SC_AC_OP_CRYPTO], &bNumber) == SC_AC_CHV) ) { bBuf[len++] = 0x83; bBuf[len++] = 0x01; bBuf[len++] = 0x2A; /* INS byte for the sign/decrypt APDU */ bBuf[len++] = bNumber & 0x07; /* pin ref */ } sc_file_set_sec_attr(file, bBuf, len); } return iso_ops->create_file(card, file); } static int setcos_create_file(sc_card_t *card, sc_file_t *file) { if (card->type == SC_CARD_TYPE_SETCOS_44 || SETCOS_IS_EID_APPLET(card)) return setcos_create_file_44(card, file); if (file->prop_attr_len == 0) sc_file_set_prop_attr(file, (const u8 *) "\x03\x00\x00", 3); if (file->sec_attr_len == 0) { int idx[6], i; u8 buf[6]; if (file->type == SC_FILE_TYPE_DF) { const int df_idx[6] = { SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = df_idx[i]; } else { const int ef_idx[6] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = ef_idx[i]; } for (i = 0; i < 6; i++) { const struct sc_acl_entry *entry; entry = sc_file_get_acl_entry(file, idx[i]); buf[i] = acl_to_byte(entry); } sc_file_set_sec_attr(file, buf, 6); } return iso_ops->create_file(card, file); } static int setcos_set_security_env2(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 *p; int r, locked = 0; assert(card != NULL && env != NULL); if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) { if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) { sc_log(card->ctx, "symmetric keyref not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } if (se_num > 0) { sc_log(card->ctx, "restore security environment not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0); switch (env->operation) { case SC_SEC_OPERATION_DECIPHER: /* Should be 0x81 */ apdu.p1 = 0x41; apdu.p2 = 0xB8; break; case SC_SEC_OPERATION_SIGN: /* Should be 0x41 */ apdu.p1 = ((card->type == SC_CARD_TYPE_SETCOS_FINEID_V2) || (card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048) || (card->type == SC_CARD_TYPE_SETCOS_44) || (card->type == SC_CARD_TYPE_SETCOS_NIDEL) || SETCOS_IS_EID_APPLET(card)) ? 0x41 : 0x81; apdu.p2 = 0xB6; break; default: return SC_ERROR_INVALID_ARGUMENTS; } apdu.le = 0; p = sbuf; if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = env->algorithm_ref & 0xFF; } if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) { *p++ = 0x81; *p++ = env->file_ref.len; memcpy(p, env->file_ref.value, env->file_ref.len); p += env->file_ref.len; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT && !(card->type == SC_CARD_TYPE_SETCOS_NIDEL || card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048)) { if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) *p++ = 0x83; else *p++ = 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; apdu.resplen = 0; 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(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(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 setcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { if (env->flags & SC_SEC_ENV_ALG_PRESENT) { sc_security_env_t tmp; tmp = *env; tmp.flags &= ~SC_SEC_ENV_ALG_PRESENT; tmp.flags |= SC_SEC_ENV_ALG_REF_PRESENT; if (tmp.algorithm != SC_ALGORITHM_RSA) { sc_log(card->ctx, "Only RSA algorithm supported.\n"); return SC_ERROR_NOT_SUPPORTED; } switch (card->type) { case SC_CARD_TYPE_SETCOS_PKI: case SC_CARD_TYPE_SETCOS_FINEID: case SC_CARD_TYPE_SETCOS_FINEID_V2_2048: case SC_CARD_TYPE_SETCOS_NIDEL: case SC_CARD_TYPE_SETCOS_44: case SC_CARD_TYPE_SETCOS_EID_V2_0: case SC_CARD_TYPE_SETCOS_EID_V2_1: break; default: sc_log(card->ctx, "Card does not support RSA.\n"); return SC_ERROR_NOT_SUPPORTED; break; } tmp.algorithm_ref = 0x00; /* potential FIXME: return an error, if an unsupported * pad or hash was requested, although this shouldn't happen. */ if (env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1) tmp.algorithm_ref = 0x02; if (tmp.algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) tmp.algorithm_ref |= 0x10; return setcos_set_security_env2(card, &tmp, se_num); } return setcos_set_security_env2(card, env, se_num); } static void add_acl_entry(sc_file_t *file, int op, u8 byte) { unsigned int method, key_ref = SC_AC_KEY_REF_NONE; switch (byte >> 4) { case 0: method = SC_AC_NONE; break; case 1: method = SC_AC_CHV; key_ref = 1; break; case 2: method = SC_AC_CHV; key_ref = 2; break; case 4: method = SC_AC_TERM; break; case 15: method = SC_AC_NEVER; break; default: method = SC_AC_UNKNOWN; break; } sc_file_add_acl_entry(file, op, method, key_ref); } static void parse_sec_attr(sc_file_t *file, const u8 * buf, size_t len) { int i; int idx[6]; if (len < 6) return; if (file->type == SC_FILE_TYPE_DF) { const int df_idx[6] = { SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = df_idx[i]; } else { const int ef_idx[6] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = ef_idx[i]; } for (i = 0; i < 6; i++) add_acl_entry(file, idx[i], buf[i]); } static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) { /* OpenSc Operation values for each command operation-type */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; u8 bValue; int i; int iKeyRef = 0; int iMethod; int iPinCount; int iOffset = 0; int iOperation; const int* p_idx; /* Check all sub-AC definitions within the total AC */ while (len > 1) { /* minimum length = 2 */ size_t iACLen = buf[iOffset] & 0x0F; if (iACLen > len) break; iMethod = SC_AC_NONE; /* default no authentication required */ if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ size_t iParmLen = 1; /* command-byte is always present */ size_t iKeyLen = 0; /* Encryption key is optional */ if (buf[iOffset] & 0x20) iKeyLen++; if (buf[iOffset+1] & 0x40) iParmLen++; if (buf[iOffset+1] & 0x20) iParmLen++; if (buf[iOffset+1] & 0x10) iParmLen++; if (buf[iOffset+1] & 0x08) iParmLen++; /* Get KeyNumber if available */ if(iKeyLen) { int iSC; if (len < 1+(size_t)iACLen) break; iSC = buf[iOffset+iACLen]; switch( (iSC>>5) & 0x03 ){ case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ } /* Get PinNumber if available */ if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ if (len < 1+1+1+(size_t)iParmLen) break; iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ iMethod = SC_AC_CHV; } /* Convert SETCOS command to OpenSC command group */ if (len < 1+2) break; switch(buf[iOffset+2]){ case 0x2A: /* crypto operation */ iOperation = SC_AC_OP_CRYPTO; break; case 0x46: /* key-generation operation */ iOperation = SC_AC_OP_UPDATE; break; default: iOperation = SC_AC_OP_SELECT; break; } sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); } else { /* AC in simple coding */ /* Initial AC is treated as an operational AC */ /* Get specific Cmd groups for specified file-type */ switch (file->type) { case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* EF */ p_idx = ef_idx; break; } /* Encryption key present ? */ iPinCount = iACLen - 1; if (buf[iOffset] & 0x20) { int iSC; if (len < 1 + (size_t)iACLen) break; iSC = buf[iOffset + iACLen]; switch( (iSC>>5) & 0x03 ) { case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ iPinCount--; /* one byte used for keyReference */ } /* Pin present ? */ if ( iPinCount > 0 ) { if (len < 1 + 2) break; iKeyRef = buf[iOffset + 2]; /* pin ref */ iMethod = SC_AC_CHV; } /* Add AC for each command-operationType into OpenSc structure */ bValue = buf[iOffset + 1]; for (i = 0; i < 8; i++) { if((bValue & 1) && (p_idx[i] >= 0)) sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); bValue >>= 1; } } /* Current field treated, get next AC sub-field */ iOffset += iACLen +1; /* AC + PTL-byte */ len -= iACLen +1; } } static int setcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file) { int r; r = iso_ops->select_file(card, in_path, file); /* Certain FINeID cards for organisations return 6A88 instead of 6A82 for missing files */ if (card->flags & _FINEID_BROKEN_SELECT_FLAG && r == SC_ERROR_DATA_OBJECT_NOT_FOUND) return SC_ERROR_FILE_NOT_FOUND; if (r) return r; if (file != NULL) { if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) parse_sec_attr_44(*file, (*file)->sec_attr, (*file)->sec_attr_len); else parse_sec_attr(*file, (*file)->sec_attr, (*file)->sec_attr_len); } return 0; } static int setcos_list_files(sc_card_t *card, u8 * buf, size_t buflen) { sc_apdu_t apdu; int r; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, 0, 0); if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) apdu.cla = 0x80; apdu.resp = buf; apdu.resplen = buflen; apdu.le = buflen > 256 ? 256 : buflen; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (card->type == SC_CARD_TYPE_SETCOS_44 && apdu.sw1 == 0x6A && apdu.sw2 == 0x82) return 0; /* no files found */ if (apdu.resplen == 0) return sc_check_sw(card, apdu.sw1, apdu.sw2); return apdu.resplen; } static int setcos_process_fci(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t buflen) { int r = iso_ops->process_fci(card, file, buf, buflen); /* SetCOS 4.4: RSA key file is an internal EF but it's * file descriptor doesn't seem to follow ISO7816. */ if (r >= 0 && (card->type == SC_CARD_TYPE_SETCOS_44 || SETCOS_IS_EID_APPLET(card))) { const u8 *tag; size_t taglen = 1; tag = (u8 *) sc_asn1_find_tag(card->ctx, buf, buflen, 0x82, &taglen); if (tag != NULL && taglen == 1 && *tag == 0x11) file->type = SC_FILE_TYPE_INTERNAL_EF; } return r; } /* Write internal data, e.g. add default pin-records to pin-file */ static int setcos_putdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj) { int r; struct sc_apdu apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); memset(&apdu, 0, sizeof(apdu)); apdu.cse = SC_APDU_CASE_3_SHORT; apdu.cla = 0x00; apdu.ins = 0xDA; apdu.p1 = data_obj->P1; apdu.p2 = data_obj->P2; apdu.lc = data_obj->DataLen; apdu.datalen = data_obj->DataLen; apdu.data = data_obj->Data; r = sc_transmit_apdu(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, "PUT_DATA returned error"); LOG_FUNC_RETURN(card->ctx, r); } /* Read internal data, e.g. get RSA public key */ static int setcos_getdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj) { int r; struct sc_apdu apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); memset(&apdu, 0, sizeof(apdu)); apdu.cse = SC_APDU_CASE_2_SHORT; apdu.cla = 0x00; apdu.ins = 0xCA; /* GET DATA */ apdu.p1 = data_obj->P1; apdu.p2 = data_obj->P2; apdu.lc = 0; apdu.datalen = 0; apdu.data = data_obj->Data; apdu.le = 256; apdu.resp = data_obj->Data; apdu.resplen = data_obj->DataLen; r = sc_transmit_apdu(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_DATA returned error"); if (apdu.resplen > data_obj->DataLen) r = SC_ERROR_WRONG_LENGTH; else data_obj->DataLen = apdu.resplen; LOG_FUNC_RETURN(card->ctx, r); } /* Generate or store a key */ static int setcos_generate_store_key(sc_card_t *card, struct sc_cardctl_setcos_gen_store_key_info *data) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int r, len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Setup key-generation parameters */ len = 0; if (data->op_type == OP_TYPE_GENERATE) sbuf[len++] = 0x92; /* algo ID: RSA CRT */ else sbuf[len++] = 0x9A; /* algo ID: EXTERNALLY GENERATED RSA CRT */ sbuf[len++] = 0x00; sbuf[len++] = data->mod_len / 256; /* 2 bytes for modulus bitlength */ sbuf[len++] = data->mod_len % 256; sbuf[len++] = data->pubexp_len / 256; /* 2 bytes for pubexp bitlength */ sbuf[len++] = data->pubexp_len % 256; memcpy(sbuf + len, data->pubexp, (data->pubexp_len + 7) / 8); len += (data->pubexp_len + 7) / 8; if (data->op_type == OP_TYPE_STORE) { sbuf[len++] = data->primep_len / 256; sbuf[len++] = data->primep_len % 256; memcpy(sbuf + len, data->primep, (data->primep_len + 7) / 8); len += (data->primep_len + 7) / 8; sbuf[len++] = data->primeq_len / 256; sbuf[len++] = data->primeq_len % 256; memcpy(sbuf + len, data->primeq, (data->primeq_len + 7) / 8); len += (data->primeq_len + 7) / 8; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.cla = 0x00; apdu.data = sbuf; apdu.datalen = len; apdu.lc = len; r = sc_transmit_apdu(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, "STORE/GENERATE_KEY returned error"); LOG_FUNC_RETURN(card->ctx, r); } static int setcos_activate_file(sc_card_t *card) { int r; u8 sbuf[2]; sc_apdu_t apdu; sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x44, 0x00, 0x00); apdu.data = sbuf; r = sc_transmit_apdu(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, "ACTIVATE_FILE returned error"); LOG_FUNC_RETURN(card->ctx, r); } static int setcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { if (card->type != SC_CARD_TYPE_SETCOS_44 && !SETCOS_IS_EID_APPLET(card)) return SC_ERROR_NOT_SUPPORTED; switch(cmd) { case SC_CARDCTL_SETCOS_PUTDATA: return setcos_putdata(card, (struct sc_cardctl_setcos_data_obj*) ptr); break; case SC_CARDCTL_SETCOS_GETDATA: return setcos_getdata(card, (struct sc_cardctl_setcos_data_obj*) ptr); break; case SC_CARDCTL_SETCOS_GENERATE_STORE_KEY: return setcos_generate_store_key(card, (struct sc_cardctl_setcos_gen_store_key_info *) ptr); case SC_CARDCTL_SETCOS_ACTIVATE_FILE: return setcos_activate_file(card); } return SC_ERROR_NOT_SUPPORTED; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); setcos_ops = *iso_drv->ops; setcos_ops.match_card = setcos_match_card; setcos_ops.init = setcos_init; if (iso_ops == NULL) iso_ops = iso_drv->ops; setcos_ops.create_file = setcos_create_file; setcos_ops.set_security_env = setcos_set_security_env; setcos_ops.select_file = setcos_select_file; setcos_ops.list_files = setcos_list_files; setcos_ops.process_fci = setcos_process_fci; setcos_ops.construct_fci = setcos_construct_fci; setcos_ops.card_ctl = setcos_card_ctl; return &setcos_drv; } struct sc_card_driver *sc_get_setcos_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1297_0
crossvul-cpp_data_good_2648_1
/* * Copyright (c) 1998-2007 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) * IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com> * DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net> */ /* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "af.h" #include "oui.h" #define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9) #define LLDP_EXTRACT_LEN(x) ((x)&0x01ff) /* * TLV type codes */ #define LLDP_END_TLV 0 #define LLDP_CHASSIS_ID_TLV 1 #define LLDP_PORT_ID_TLV 2 #define LLDP_TTL_TLV 3 #define LLDP_PORT_DESCR_TLV 4 #define LLDP_SYSTEM_NAME_TLV 5 #define LLDP_SYSTEM_DESCR_TLV 6 #define LLDP_SYSTEM_CAP_TLV 7 #define LLDP_MGMT_ADDR_TLV 8 #define LLDP_PRIVATE_TLV 127 static const struct tok lldp_tlv_values[] = { { LLDP_END_TLV, "End" }, { LLDP_CHASSIS_ID_TLV, "Chassis ID" }, { LLDP_PORT_ID_TLV, "Port ID" }, { LLDP_TTL_TLV, "Time to Live" }, { LLDP_PORT_DESCR_TLV, "Port Description" }, { LLDP_SYSTEM_NAME_TLV, "System Name" }, { LLDP_SYSTEM_DESCR_TLV, "System Description" }, { LLDP_SYSTEM_CAP_TLV, "System Capabilities" }, { LLDP_MGMT_ADDR_TLV, "Management Address" }, { LLDP_PRIVATE_TLV, "Organization specific" }, { 0, NULL} }; /* * Chassis ID subtypes */ #define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1 #define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2 #define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3 #define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4 #define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5 #define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6 #define LLDP_CHASSIS_LOCAL_SUBTYPE 7 static const struct tok lldp_chassis_subtype_values[] = { { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"}, { LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"}, { LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"}, { LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"}, { LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"}, { LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"}, { LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"}, { 0, NULL} }; /* * Port ID subtypes */ #define LLDP_PORT_INTF_ALIAS_SUBTYPE 1 #define LLDP_PORT_PORT_COMP_SUBTYPE 2 #define LLDP_PORT_MAC_ADDR_SUBTYPE 3 #define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4 #define LLDP_PORT_INTF_NAME_SUBTYPE 5 #define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6 #define LLDP_PORT_LOCAL_SUBTYPE 7 static const struct tok lldp_port_subtype_values[] = { { LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"}, { LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"}, { LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"}, { LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"}, { LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"}, { LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"}, { LLDP_PORT_LOCAL_SUBTYPE, "Local"}, { 0, NULL} }; /* * System Capabilities */ #define LLDP_CAP_OTHER (1 << 0) #define LLDP_CAP_REPEATER (1 << 1) #define LLDP_CAP_BRIDGE (1 << 2) #define LLDP_CAP_WLAN_AP (1 << 3) #define LLDP_CAP_ROUTER (1 << 4) #define LLDP_CAP_PHONE (1 << 5) #define LLDP_CAP_DOCSIS (1 << 6) #define LLDP_CAP_STATION_ONLY (1 << 7) static const struct tok lldp_cap_values[] = { { LLDP_CAP_OTHER, "Other"}, { LLDP_CAP_REPEATER, "Repeater"}, { LLDP_CAP_BRIDGE, "Bridge"}, { LLDP_CAP_WLAN_AP, "WLAN AP"}, { LLDP_CAP_ROUTER, "Router"}, { LLDP_CAP_PHONE, "Telephone"}, { LLDP_CAP_DOCSIS, "Docsis"}, { LLDP_CAP_STATION_ONLY, "Station Only"}, { 0, NULL} }; #define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1 #define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2 #define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3 #define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4 #define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10 #define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11 #define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12 #define LLDP_PRIVATE_8021_SUBTYPE_EVB 13 #define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14 static const struct tok lldp_8021_subtype_values[] = { { LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"}, { LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"}, { LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"}, { LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"}, { LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"}, { LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"}, { LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"}, { LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"}, { LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"}, { LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"}, { LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"}, { 0, NULL} }; #define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1) #define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2) static const struct tok lldp_8021_port_protocol_id_values[] = { { LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"}, { LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"}, { 0, NULL} }; #define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1 #define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2 #define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3 #define LLDP_PRIVATE_8023_SUBTYPE_MTU 4 static const struct tok lldp_8023_subtype_values[] = { { LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"}, { LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"}, { LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"}, { LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"}, { 0, NULL} }; #define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1 #define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2 #define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3 #define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11 static const struct tok lldp_tia_subtype_values[] = { { LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" }, { LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" }, { LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" }, { LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" }, { 0, NULL} }; #define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1 #define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2 static const struct tok lldp_tia_location_altitude_type_values[] = { { LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"}, { LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"}, { 0, NULL} }; /* ANSI/TIA-1057 - Annex B */ #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6 static const struct tok lldp_tia_location_lci_catype_values[] = { { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"}, { 0, NULL} }; static const struct tok lldp_tia_location_lci_what_values[] = { { 0, "location of DHCP server"}, { 1, "location of the network element believed to be closest to the client"}, { 2, "location of the client"}, { 0, NULL} }; /* * From RFC 3636 - dot3MauType */ #define LLDP_MAU_TYPE_UNKNOWN 0 #define LLDP_MAU_TYPE_AUI 1 #define LLDP_MAU_TYPE_10BASE_5 2 #define LLDP_MAU_TYPE_FOIRL 3 #define LLDP_MAU_TYPE_10BASE_2 4 #define LLDP_MAU_TYPE_10BASE_T 5 #define LLDP_MAU_TYPE_10BASE_FP 6 #define LLDP_MAU_TYPE_10BASE_FB 7 #define LLDP_MAU_TYPE_10BASE_FL 8 #define LLDP_MAU_TYPE_10BROAD36 9 #define LLDP_MAU_TYPE_10BASE_T_HD 10 #define LLDP_MAU_TYPE_10BASE_T_FD 11 #define LLDP_MAU_TYPE_10BASE_FL_HD 12 #define LLDP_MAU_TYPE_10BASE_FL_FD 13 #define LLDP_MAU_TYPE_100BASE_T4 14 #define LLDP_MAU_TYPE_100BASE_TX_HD 15 #define LLDP_MAU_TYPE_100BASE_TX_FD 16 #define LLDP_MAU_TYPE_100BASE_FX_HD 17 #define LLDP_MAU_TYPE_100BASE_FX_FD 18 #define LLDP_MAU_TYPE_100BASE_T2_HD 19 #define LLDP_MAU_TYPE_100BASE_T2_FD 20 #define LLDP_MAU_TYPE_1000BASE_X_HD 21 #define LLDP_MAU_TYPE_1000BASE_X_FD 22 #define LLDP_MAU_TYPE_1000BASE_LX_HD 23 #define LLDP_MAU_TYPE_1000BASE_LX_FD 24 #define LLDP_MAU_TYPE_1000BASE_SX_HD 25 #define LLDP_MAU_TYPE_1000BASE_SX_FD 26 #define LLDP_MAU_TYPE_1000BASE_CX_HD 27 #define LLDP_MAU_TYPE_1000BASE_CX_FD 28 #define LLDP_MAU_TYPE_1000BASE_T_HD 29 #define LLDP_MAU_TYPE_1000BASE_T_FD 30 #define LLDP_MAU_TYPE_10GBASE_X 31 #define LLDP_MAU_TYPE_10GBASE_LX4 32 #define LLDP_MAU_TYPE_10GBASE_R 33 #define LLDP_MAU_TYPE_10GBASE_ER 34 #define LLDP_MAU_TYPE_10GBASE_LR 35 #define LLDP_MAU_TYPE_10GBASE_SR 36 #define LLDP_MAU_TYPE_10GBASE_W 37 #define LLDP_MAU_TYPE_10GBASE_EW 38 #define LLDP_MAU_TYPE_10GBASE_LW 39 #define LLDP_MAU_TYPE_10GBASE_SW 40 static const struct tok lldp_mau_types_values[] = { { LLDP_MAU_TYPE_UNKNOWN, "Unknown"}, { LLDP_MAU_TYPE_AUI, "AUI"}, { LLDP_MAU_TYPE_10BASE_5, "10BASE_5"}, { LLDP_MAU_TYPE_FOIRL, "FOIRL"}, { LLDP_MAU_TYPE_10BASE_2, "10BASE2"}, { LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"}, { LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"}, { LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"}, { LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"}, { LLDP_MAU_TYPE_10BROAD36, "10BROAD36"}, { LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"}, { LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"}, { LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"}, { LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"}, { LLDP_MAU_TYPE_100BASE_T4, "100BASET4"}, { LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"}, { LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"}, { LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"}, { LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"}, { LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"}, { LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"}, { LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"}, { LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"}, { LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"}, { LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"}, { LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"}, { LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"}, { LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"}, { LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"}, { LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"}, { LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"}, { LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"}, { LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"}, { LLDP_MAU_TYPE_10GBASE_R, "10GBASER"}, { LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"}, { LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"}, { LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"}, { LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"}, { LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"}, { LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"}, { LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"}, { 0, NULL} }; #define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0) #define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1) static const struct tok lldp_8023_autonegotiation_values[] = { { LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"}, { LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"}, { 0, NULL} }; #define LLDP_TIA_CAPABILITY_MED (1 << 0) #define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1) #define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2) #define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3) #define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4) #define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5) static const struct tok lldp_tia_capabilities_values[] = { { LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"}, { LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"}, { LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"}, { LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"}, { LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"}, { LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"}, { 0, NULL} }; #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1 #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2 #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3 #define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4 static const struct tok lldp_tia_device_type_values[] = { { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"}, { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"}, { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"}, { LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"}, { 0, NULL} }; #define LLDP_TIA_APPLICATION_TYPE_VOICE 1 #define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2 #define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3 #define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4 #define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5 #define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6 #define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7 #define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8 static const struct tok lldp_tia_application_type_values[] = { { LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"}, { LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"}, { LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"}, { LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"}, { LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"}, { LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"}, { LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"}, { LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"}, { 0, NULL} }; #define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5) #define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6) #define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7) static const struct tok lldp_tia_network_policy_bits_values[] = { { LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"}, { LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"}, { LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"}, { 0, NULL} }; #define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1) #define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6) #define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f) #define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1 #define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2 #define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3 static const struct tok lldp_tia_location_data_format_values[] = { { LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"}, { LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"}, { LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"}, { 0, NULL} }; #define LLDP_TIA_LOCATION_DATUM_WGS_84 1 #define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2 #define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3 static const struct tok lldp_tia_location_datum_type_values[] = { { LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"}, { LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"}, { LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"}, { 0, NULL} }; #define LLDP_TIA_POWER_SOURCE_PSE 1 #define LLDP_TIA_POWER_SOURCE_LOCAL 2 #define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3 static const struct tok lldp_tia_power_source_values[] = { { LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"}, { LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"}, { LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"}, { 0, NULL} }; #define LLDP_TIA_POWER_PRIORITY_CRITICAL 1 #define LLDP_TIA_POWER_PRIORITY_HIGH 2 #define LLDP_TIA_POWER_PRIORITY_LOW 3 static const struct tok lldp_tia_power_priority_values[] = { { LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"}, { LLDP_TIA_POWER_PRIORITY_HIGH, "high"}, { LLDP_TIA_POWER_PRIORITY_LOW, "low"}, { 0, NULL} }; #define LLDP_TIA_POWER_VAL_MAX 1024 static const struct tok lldp_tia_inventory_values[] = { { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" }, { 0, NULL} }; /* * From RFC 3636 - ifMauAutoNegCapAdvertisedBits */ #define LLDP_MAU_PMD_OTHER (1 << 15) #define LLDP_MAU_PMD_10BASE_T (1 << 14) #define LLDP_MAU_PMD_10BASE_T_FD (1 << 13) #define LLDP_MAU_PMD_100BASE_T4 (1 << 12) #define LLDP_MAU_PMD_100BASE_TX (1 << 11) #define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10) #define LLDP_MAU_PMD_100BASE_T2 (1 << 9) #define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8) #define LLDP_MAU_PMD_FDXPAUSE (1 << 7) #define LLDP_MAU_PMD_FDXAPAUSE (1 << 6) #define LLDP_MAU_PMD_FDXSPAUSE (1 << 5) #define LLDP_MAU_PMD_FDXBPAUSE (1 << 4) #define LLDP_MAU_PMD_1000BASE_X (1 << 3) #define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2) #define LLDP_MAU_PMD_1000BASE_T (1 << 1) #define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0) static const struct tok lldp_pmd_capability_values[] = { { LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"}, { LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"}, { LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"}, { LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"}, { LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"}, { LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"}, { LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"}, { LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"}, { LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"}, { LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"}, { LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"}, { LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"}, { LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"}, { LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"}, { LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"}, { 0, NULL} }; #define LLDP_MDI_PORT_CLASS (1 << 0) #define LLDP_MDI_POWER_SUPPORT (1 << 1) #define LLDP_MDI_POWER_STATE (1 << 2) #define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3) static const struct tok lldp_mdi_values[] = { { LLDP_MDI_PORT_CLASS, "PSE"}, { LLDP_MDI_POWER_SUPPORT, "supported"}, { LLDP_MDI_POWER_STATE, "enabled"}, { LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"}, { 0, NULL} }; #define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1 #define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2 static const struct tok lldp_mdi_power_pairs_values[] = { { LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"}, { LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"}, { 0, NULL} }; #define LLDP_MDI_POWER_CLASS0 1 #define LLDP_MDI_POWER_CLASS1 2 #define LLDP_MDI_POWER_CLASS2 3 #define LLDP_MDI_POWER_CLASS3 4 #define LLDP_MDI_POWER_CLASS4 5 static const struct tok lldp_mdi_power_class_values[] = { { LLDP_MDI_POWER_CLASS0, "class0"}, { LLDP_MDI_POWER_CLASS1, "class1"}, { LLDP_MDI_POWER_CLASS2, "class2"}, { LLDP_MDI_POWER_CLASS3, "class3"}, { LLDP_MDI_POWER_CLASS4, "class4"}, { 0, NULL} }; #define LLDP_AGGREGATION_CAPABILTIY (1 << 0) #define LLDP_AGGREGATION_STATUS (1 << 1) static const struct tok lldp_aggregation_values[] = { { LLDP_AGGREGATION_CAPABILTIY, "supported"}, { LLDP_AGGREGATION_STATUS, "enabled"}, { 0, NULL} }; /* * DCBX protocol subtypes. */ #define LLDP_DCBX_SUBTYPE_1 1 #define LLDP_DCBX_SUBTYPE_2 2 static const struct tok lldp_dcbx_subtype_values[] = { { LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" }, { LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" }, { 0, NULL} }; #define LLDP_DCBX_CONTROL_TLV 1 #define LLDP_DCBX_PRIORITY_GROUPS_TLV 2 #define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3 #define LLDP_DCBX_APPLICATION_TLV 4 /* * Interface numbering subtypes. */ #define LLDP_INTF_NUMB_IFX_SUBTYPE 2 #define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3 static const struct tok lldp_intf_numb_subtype_values[] = { { LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" }, { LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" }, { 0, NULL} }; #define LLDP_INTF_NUM_LEN 5 #define LLDP_EVB_MODE_NOT_SUPPORTED 0 #define LLDP_EVB_MODE_EVB_BRIDGE 1 #define LLDP_EVB_MODE_EVB_STATION 2 #define LLDP_EVB_MODE_RESERVED 3 static const struct tok lldp_evb_mode_values[]={ { LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"}, { LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"}, { LLDP_EVB_MODE_EVB_STATION, "EVB Staion"}, { LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"}, { 0, NULL}, }; #define NO_OF_BITS 8 #define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25 #define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6 #define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5 #define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9 #define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8 #define LLDP_IANA_SUBTYPE_MUDURL 1 static const struct tok lldp_iana_subtype_values[] = { { LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" }, { 0, NULL } }; static void print_ets_priority_assignment_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t Priority Assignment Table")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4, ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f)); } static void print_tc_bandwidth_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t TC Bandwidth Table")); ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7])); } static void print_tsa_assignment_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t TSA Assignment Table")); ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7])); } /* * Print IEEE 802.1 private extensions. (802.1AB annex E) */ static int lldp_private_8021_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; u_int sublen; u_int tval; uint8_t i; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8021_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t port vlan id (PVID): %u", EXTRACT_16BITS(tptr + 4))); break; case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)", EXTRACT_16BITS(tptr+5), bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)), *(tptr + 4))); break; case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4))); if (tlv_len < 7) { return hexdump; } sublen = *(tptr+6); if (tlv_len < 7+sublen) { return hexdump; } ND_PRINT((ndo, "\n\t vlan name: ")); safeputs(ndo, tptr + 7, sublen); break; case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY: if (tlv_len < 5) { return hexdump; } sublen = *(tptr+4); if (tlv_len < 5+sublen) { return hexdump; } ND_PRINT((ndo, "\n\t protocol identity: ")); safeputs(ndo, tptr + 5, sublen); break; case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){ return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); tval=*(tptr+5); ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); break; case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) { return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d", tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07)); /*Print Priority Assignment Table*/ print_ets_priority_assignment_table(ndo, tptr + 5); /*Print TC Bandwidth Table*/ print_tc_bandwidth_table(ndo, tptr + 9); /* Print TSA Assignment Table */ print_tsa_assignment_table(ndo, tptr + 17); break; case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) { return hexdump; } ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4))); /*Print Priority Assignment Table */ print_ets_priority_assignment_table(ndo, tptr + 5); /*Print TC Bandwidth Table */ print_tc_bandwidth_table(ndo, tptr + 9); /* Print TSA Assignment Table */ print_tsa_assignment_table(ndo, tptr + 17); break; case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) { return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ", tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f))); ND_PRINT((ndo, "\n\t PFC Enable")); tval=*(tptr+5); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); break; case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) { return hexdump; } ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4))); if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){ return hexdump; } /* Length of Application Priority Table */ sublen=tlv_len-5; if(sublen%3!=0){ return hexdump; } i=0; ND_PRINT((ndo, "\n\t Application Priority Table")); while(i<sublen) { tval=*(tptr+i+5); ND_PRINT((ndo, "\n\t Priority: %d, RES: %d, Sel: %d", tval >> 5, (tval >> 3) & 0x03, (tval & 0x07))); ND_PRINT((ndo, "Protocol ID: %d", EXTRACT_16BITS(tptr + i + 5))); i=i+3; } break; case LLDP_PRIVATE_8021_SUBTYPE_EVB: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){ return hexdump; } ND_PRINT((ndo, "\n\t EVB Bridge Status")); tval=*(tptr+4); ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d", tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01)); ND_PRINT((ndo, "\n\t EVB Station Status")); tval=*(tptr+5); ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d", tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03)); tval=*(tptr+6); ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f)); tval=*(tptr+7); ND_PRINT((ndo, "EVB Mode: %s [%d]", tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6)); ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f)); tval=*(tptr+8); ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f)); break; case LLDP_PRIVATE_8021_SUBTYPE_CDCP: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){ return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ", tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01)); ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff)); sublen=tlv_len-8; if(sublen%3!=0) { return hexdump; } i=0; while(i<sublen) { tval=EXTRACT_24BITS(tptr+i+8); ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d", tval >> 12, tval & 0x000fff)); i=i+3; } break; default: hexdump = TRUE; break; } return hexdump; } /* * Print IEEE 802.3 private extensions. (802.3bc) */ static int lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } /* * Extract 34bits of latitude/longitude coordinates. */ static uint64_t lldp_extract_latlon(const u_char *tptr) { uint64_t latlon; latlon = *tptr & 0x3; latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1); return latlon; } /* objects defined in IANA subtype 00 00 5e * (right now there is only one) */ static int lldp_private_iana_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 8) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_iana_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_IANA_SUBTYPE_MUDURL: ND_PRINT((ndo, "\n\t MUD-URL=")); (void)fn_printn(ndo, tptr+4, tlv_len-4, NULL); break; default: hexdump=TRUE; } return hexdump; } /* * Print private TIA extensions. */ static int lldp_private_tia_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; uint8_t location_format; uint16_t power_val; u_int lci_len; uint8_t ca_type, ca_len; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_tia_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)", bittok2str(lldp_tia_capabilities_values, "none", EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4))); ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)", tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)), *(tptr + 6))); break; case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY: if (tlv_len < 8) { return hexdump; } ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)", tok2str(lldp_tia_application_type_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, ", Flags [%s]", bittok2str( lldp_tia_network_policy_bits_values, "none", *(tptr + 5)))); ND_PRINT((ndo, "\n\t Vlan id %u", LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5)))); ND_PRINT((ndo, ", L2 priority %u", LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6)))); ND_PRINT((ndo, ", DSCP value %u", LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6)))); break; case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID: if (tlv_len < 5) { return hexdump; } location_format = *(tptr+4); ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)", tok2str(lldp_tia_location_data_format_values, "unknown", location_format), location_format)); switch (location_format) { case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED: if (tlv_len < 21) { return hexdump; } ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64, (*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5))); ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64, (*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10))); ND_PRINT((ndo, "\n\t Altitude type %s (%u)", tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)), (*(tptr + 15) >> 4))); ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x", (EXTRACT_16BITS(tptr+15)>>6)&0x3f, ((EXTRACT_32BITS(tptr + 16) & 0x3fffffff)))); ND_PRINT((ndo, "\n\t Datum %s (0x%02x)", tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)), *(tptr + 20))); break; case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS: if (tlv_len < 6) { return hexdump; } lci_len = *(tptr+5); if (lci_len < 3) { return hexdump; } if (tlv_len < 7+lci_len) { return hexdump; } ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ", lci_len, tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)), *(tptr + 6))); /* Country code */ safeputs(ndo, tptr + 7, 2); lci_len = lci_len-3; tptr = tptr + 9; /* Decode each civic address element */ while (lci_len > 0) { if (lci_len < 2) { return hexdump; } ca_type = *(tptr); ca_len = *(tptr+1); tptr += 2; lci_len -= 2; ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ", tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type), ca_type, ca_len)); /* basic sanity check */ if ( ca_type == 0 || ca_len == 0) { return hexdump; } if (lci_len < ca_len) { return hexdump; } safeputs(ndo, tptr, ca_len); tptr += ca_len; lci_len -= ca_len; } break; case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN: ND_PRINT((ndo, "\n\t ECS ELIN id ")); safeputs(ndo, tptr + 5, tlv_len - 5); break; default: ND_PRINT((ndo, "\n\t Location ID ")); print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5); } break; case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t Power type [%s]", (*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device")); ND_PRINT((ndo, ", Power source [%s]", tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4))); ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)", tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f), *(tptr + 4) & 0x0f)); power_val = EXTRACT_16BITS(tptr+5); if (power_val < LLDP_TIA_POWER_VAL_MAX) { ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10)); } else { ND_PRINT((ndo, ", Power %u (Reserved)", power_val)); } break; case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID: ND_PRINT((ndo, "\n\t %s ", tok2str(lldp_tia_inventory_values, "unknown", subtype))); safeputs(ndo, tptr + 4, tlv_len - 4); break; default: hexdump = TRUE; break; } return hexdump; } /* * Print DCBX Protocol fields (V 1.01). */ static int lldp_private_dcbx_print(netdissect_options *ndo, const u_char *pptr, u_int len) { int subtype, hexdump = FALSE; uint8_t tval; uint16_t tlv; uint32_t i, pgval, uval; u_int tlen, tlv_type, tlv_len; const u_char *tptr, *mptr; if (len < 4) { return hexdump; } subtype = *(pptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_dcbx_subtype_values, "unknown", subtype), subtype)); /* by passing old version */ if (subtype == LLDP_DCBX_SUBTYPE_1) return TRUE; tptr = pptr + 4; tlen = len - 4; while (tlen >= sizeof(tlv)) { ND_TCHECK2(*tptr, sizeof(tlv)); tlv = EXTRACT_16BITS(tptr); tlv_type = LLDP_EXTRACT_TYPE(tlv); tlv_len = LLDP_EXTRACT_LEN(tlv); hexdump = FALSE; tlen -= sizeof(tlv); tptr += sizeof(tlv); /* loop check */ if (!tlv_type || !tlv_len) { break; } ND_TCHECK2(*tptr, tlv_len); if (tlen < tlv_len) { goto trunc; } /* decode every tlv */ switch (tlv_type) { case LLDP_DCBX_CONTROL_TLV: if (tlv_len < 10) { goto trunc; } ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)", LLDP_DCBX_CONTROL_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2))); ND_PRINT((ndo, "\n\t Acknowledgement Number: %d", EXTRACT_32BITS(tptr + 6))); break; case LLDP_DCBX_PRIORITY_GROUPS_TLV: if (tlv_len < 17) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)", LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); ND_PRINT((ndo, "\n\t Priority Allocation")); /* * Array of 8 4-bit priority group ID values; we fetch all * 32 bits and extract each nibble. */ pgval = EXTRACT_32BITS(tptr+4); for (i = 0; i <= 7; i++) { ND_PRINT((ndo, "\n\t PgId_%d: %d", i, (pgval >> (28 - 4 * i)) & 0xF)); } ND_PRINT((ndo, "\n\t Priority Group Allocation")); for (i = 0; i <= 7; i++) ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i))); ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8))); break; case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV: if (tlv_len < 6) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Priority Flow Control")); ND_PRINT((ndo, " (type 0x%x, length %d)", LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); tval = *(tptr+4); ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4))); for (i = 0; i <= 7; i++) ND_PRINT((ndo, "\n\t Priority Bit %d: %s", i, (tval & (1 << i)) ? "Enabled" : "Disabled")); ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5))); break; case LLDP_DCBX_APPLICATION_TLV: if (tlv_len < 4) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)", LLDP_DCBX_APPLICATION_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); tval = tlv_len - 4; mptr = tptr + 4; while (tval >= 6) { ND_PRINT((ndo, "\n\t Application Value")); ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x", EXTRACT_16BITS(mptr))); uval = EXTRACT_24BITS(mptr+2); ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s", (uval >> 22), (uval >> 22) ? "Socket Number" : "L2 EtherType")); ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff)); ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5))); tval = tval - 6; mptr = mptr + 6; } break; default: hexdump = TRUE; break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo, tptr, "\n\t ", tlv_len); } tlen -= tlv_len; tptr += tlv_len; } trunc: return hexdump; } static char * lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len) { uint8_t af; static char buf[BUFSIZE]; const char * (*pfunc)(netdissect_options *, const u_char *); if (len < 1) return NULL; len--; af = *tptr; switch (af) { case AFNUM_INET: if (len < 4) return NULL; /* This cannot be assigned to ipaddr_string(), which is a macro. */ pfunc = getname; break; case AFNUM_INET6: if (len < 16) return NULL; /* This cannot be assigned to ip6addr_string(), which is a macro. */ pfunc = getname6; break; case AFNUM_802: if (len < 6) return NULL; pfunc = etheraddr_string; break; default: pfunc = NULL; break; } if (!pfunc) { snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !", tok2str(af_values, "Unknown", af), af); } else { snprintf(buf, sizeof(buf), "AFI %s (%u): %s", tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1)); } return buf; } static int lldp_mgmt_addr_tlv_print(netdissect_options *ndo, const u_char *pptr, u_int len) { uint8_t mgmt_addr_len, intf_num_subtype, oid_len; const u_char *tptr; u_int tlen; char *mgmt_addr; tlen = len; tptr = pptr; if (tlen < 1) { return 0; } mgmt_addr_len = *tptr++; tlen--; if (tlen < mgmt_addr_len) { return 0; } mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len); if (mgmt_addr == NULL) { return 0; } ND_PRINT((ndo, "\n\t Management Address length %u, %s", mgmt_addr_len, mgmt_addr)); tptr += mgmt_addr_len; tlen -= mgmt_addr_len; if (tlen < LLDP_INTF_NUM_LEN) { return 0; } intf_num_subtype = *tptr; ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u", tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype), intf_num_subtype, EXTRACT_32BITS(tptr + 1))); tptr += LLDP_INTF_NUM_LEN; tlen -= LLDP_INTF_NUM_LEN; /* * The OID is optional. */ if (tlen) { oid_len = *tptr; if (tlen < oid_len) { return 0; } if (oid_len) { ND_PRINT((ndo, "\n\t OID length %u", oid_len)); safeputs(ndo, tptr + 1, oid_len); } } return 1; } void lldp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { uint8_t subtype; uint16_t tlv, cap, ena_cap; u_int oui, tlen, hexdump, tlv_type, tlv_len; const u_char *tptr; char *network_addr; tptr = pptr; tlen = len; ND_PRINT((ndo, "LLDP, length %u", len)); while (tlen >= sizeof(tlv)) { ND_TCHECK2(*tptr, sizeof(tlv)); tlv = EXTRACT_16BITS(tptr); tlv_type = LLDP_EXTRACT_TYPE(tlv); tlv_len = LLDP_EXTRACT_LEN(tlv); hexdump = FALSE; tlen -= sizeof(tlv); tptr += sizeof(tlv); if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t%s TLV (%u), length %u", tok2str(lldp_tlv_values, "Unknown", tlv_type), tlv_type, tlv_len)); } /* infinite loop check */ if (!tlv_type || !tlv_len) { break; } ND_TCHECK2(*tptr, tlv_len); if (tlen < tlv_len) { goto trunc; } switch (tlv_type) { case LLDP_CHASSIS_ID_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } subtype = *tptr; ND_PRINT((ndo, "\n\t Subtype %s (%u): ", tok2str(lldp_chassis_subtype_values, "Unknown", subtype), subtype)); switch (subtype) { case LLDP_CHASSIS_MAC_ADDR_SUBTYPE: if (tlv_len < 1+6) { goto trunc; } ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1))); break; case LLDP_CHASSIS_INTF_NAME_SUBTYPE: /* fall through */ case LLDP_CHASSIS_LOCAL_SUBTYPE: case LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE: case LLDP_CHASSIS_INTF_ALIAS_SUBTYPE: case LLDP_CHASSIS_PORT_COMP_SUBTYPE: safeputs(ndo, tptr + 1, tlv_len - 1); break; case LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE: network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1); if (network_addr == NULL) { goto trunc; } ND_PRINT((ndo, "%s", network_addr)); break; default: hexdump = TRUE; break; } } break; case LLDP_PORT_ID_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } subtype = *tptr; ND_PRINT((ndo, "\n\t Subtype %s (%u): ", tok2str(lldp_port_subtype_values, "Unknown", subtype), subtype)); switch (subtype) { case LLDP_PORT_MAC_ADDR_SUBTYPE: if (tlv_len < 1+6) { goto trunc; } ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1))); break; case LLDP_PORT_INTF_NAME_SUBTYPE: /* fall through */ case LLDP_PORT_LOCAL_SUBTYPE: case LLDP_PORT_AGENT_CIRC_ID_SUBTYPE: case LLDP_PORT_INTF_ALIAS_SUBTYPE: case LLDP_PORT_PORT_COMP_SUBTYPE: safeputs(ndo, tptr + 1, tlv_len - 1); break; case LLDP_PORT_NETWORK_ADDR_SUBTYPE: network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1); if (network_addr == NULL) { goto trunc; } ND_PRINT((ndo, "%s", network_addr)); break; default: hexdump = TRUE; break; } } break; case LLDP_TTL_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } ND_PRINT((ndo, ": TTL %us", EXTRACT_16BITS(tptr))); } break; case LLDP_PORT_DESCR_TLV: if (ndo->ndo_vflag) { ND_PRINT((ndo, ": ")); safeputs(ndo, tptr, tlv_len); } break; case LLDP_SYSTEM_NAME_TLV: /* * The system name is also print in non-verbose mode * similar to the CDP printer. */ ND_PRINT((ndo, ": ")); safeputs(ndo, tptr, tlv_len); break; case LLDP_SYSTEM_DESCR_TLV: if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t ")); safeputs(ndo, tptr, tlv_len); } break; case LLDP_SYSTEM_CAP_TLV: if (ndo->ndo_vflag) { /* * XXX - IEEE Std 802.1AB-2009 says the first octet * if a chassis ID subtype, with the system * capabilities and enabled capabilities following * it. */ if (tlv_len < 4) { goto trunc; } cap = EXTRACT_16BITS(tptr); ena_cap = EXTRACT_16BITS(tptr+2); ND_PRINT((ndo, "\n\t System Capabilities [%s] (0x%04x)", bittok2str(lldp_cap_values, "none", cap), cap)); ND_PRINT((ndo, "\n\t Enabled Capabilities [%s] (0x%04x)", bittok2str(lldp_cap_values, "none", ena_cap), ena_cap)); } break; case LLDP_MGMT_ADDR_TLV: if (ndo->ndo_vflag) { if (!lldp_mgmt_addr_tlv_print(ndo, tptr, tlv_len)) { goto trunc; } } break; case LLDP_PRIVATE_TLV: if (ndo->ndo_vflag) { if (tlv_len < 3) { goto trunc; } oui = EXTRACT_24BITS(tptr); ND_PRINT((ndo, ": OUI %s (0x%06x)", tok2str(oui_values, "Unknown", oui), oui)); switch (oui) { case OUI_IEEE_8021_PRIVATE: hexdump = lldp_private_8021_print(ndo, tptr, tlv_len); break; case OUI_IEEE_8023_PRIVATE: hexdump = lldp_private_8023_print(ndo, tptr, tlv_len); break; case OUI_IANA: hexdump = lldp_private_iana_print(ndo, tptr, tlv_len); break; case OUI_TIA: hexdump = lldp_private_tia_print(ndo, tptr, tlv_len); break; case OUI_DCBX: hexdump = lldp_private_dcbx_print(ndo, tptr, tlv_len); break; default: hexdump = TRUE; break; } } break; default: hexdump = TRUE; break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo, tptr, "\n\t ", tlv_len); } tlen -= tlv_len; tptr += tlv_len; } return; trunc: ND_PRINT((ndo, "\n\t[|LLDP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2648_1
crossvul-cpp_data_good_3956_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Bitmap Cache V2 * * 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 <stdio.h> #include <winpr/crt.h> #include <freerdp/freerdp.h> #include <freerdp/constants.h> #include <winpr/stream.h> #include <freerdp/log.h> #include <freerdp/cache/bitmap.h> #include <freerdp/gdi/bitmap.h> #include "../gdi/gdi.h" #include "../core/graphics.h" #include "bitmap.h" #define TAG FREERDP_TAG("cache.bitmap") static rdpBitmap* bitmap_cache_get(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index); static BOOL bitmap_cache_put(rdpBitmapCache* bitmap_cache, UINT32 id, UINT32 index, rdpBitmap* bitmap); static BOOL update_gdi_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { rdpBitmap* bitmap; rdpCache* cache = context->cache; if (memblt->cacheId == 0xFF) bitmap = offscreen_cache_get(cache->offscreen, memblt->cacheIndex); else bitmap = bitmap_cache_get(cache->bitmap, (BYTE)memblt->cacheId, memblt->cacheIndex); /* XP-SP2 servers sometimes ask for cached bitmaps they've never defined. */ if (bitmap == NULL) return TRUE; memblt->bitmap = bitmap; return IFCALLRESULT(TRUE, cache->bitmap->MemBlt, context, memblt); } static BOOL update_gdi_mem3blt(rdpContext* context, MEM3BLT_ORDER* mem3blt) { BYTE style; rdpBitmap* bitmap; rdpCache* cache = context->cache; rdpBrush* brush = &mem3blt->brush; BOOL ret = TRUE; if (mem3blt->cacheId == 0xFF) bitmap = offscreen_cache_get(cache->offscreen, mem3blt->cacheIndex); else bitmap = bitmap_cache_get(cache->bitmap, (BYTE)mem3blt->cacheId, mem3blt->cacheIndex); /* XP-SP2 servers sometimes ask for cached bitmaps they've never defined. */ if (!bitmap) return TRUE; style = brush->style; if (brush->style & CACHED_BRUSH) { brush->data = brush_cache_get(cache->brush, brush->index, &brush->bpp); if (!brush->data) return FALSE; brush->style = 0x03; } mem3blt->bitmap = bitmap; IFCALLRET(cache->bitmap->Mem3Blt, ret, context, mem3blt); brush->style = style; return ret; } static BOOL update_gdi_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cacheBitmap) { rdpBitmap* bitmap; rdpBitmap* prevBitmap; rdpCache* cache = context->cache; bitmap = Bitmap_Alloc(context); if (!bitmap) return FALSE; Bitmap_SetDimensions(bitmap, cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight); if (!bitmap->Decompress(context, bitmap, cacheBitmap->bitmapDataStream, cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight, cacheBitmap->bitmapBpp, cacheBitmap->bitmapLength, cacheBitmap->compressed, RDP_CODEC_ID_NONE)) { Bitmap_Free(context, bitmap); return FALSE; } if (!bitmap->New(context, bitmap)) { Bitmap_Free(context, bitmap); return FALSE; } prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex); Bitmap_Free(context, prevBitmap); return bitmap_cache_put(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex, bitmap); } static BOOL update_gdi_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cacheBitmapV2) { rdpBitmap* bitmap; rdpBitmap* prevBitmap; rdpCache* cache = context->cache; rdpSettings* settings = context->settings; bitmap = Bitmap_Alloc(context); if (!bitmap) return FALSE; if (!cacheBitmapV2->bitmapBpp) cacheBitmapV2->bitmapBpp = settings->ColorDepth; if ((settings->ColorDepth == 15) && (cacheBitmapV2->bitmapBpp == 16)) cacheBitmapV2->bitmapBpp = settings->ColorDepth; Bitmap_SetDimensions(bitmap, cacheBitmapV2->bitmapWidth, cacheBitmapV2->bitmapHeight); if (!bitmap->Decompress(context, bitmap, cacheBitmapV2->bitmapDataStream, cacheBitmapV2->bitmapWidth, cacheBitmapV2->bitmapHeight, cacheBitmapV2->bitmapBpp, cacheBitmapV2->bitmapLength, cacheBitmapV2->compressed, RDP_CODEC_ID_NONE)) { Bitmap_Free(context, bitmap); return FALSE; } prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmapV2->cacheId, cacheBitmapV2->cacheIndex); if (!bitmap->New(context, bitmap)) { Bitmap_Free(context, bitmap); return FALSE; } Bitmap_Free(context, prevBitmap); return bitmap_cache_put(cache->bitmap, cacheBitmapV2->cacheId, cacheBitmapV2->cacheIndex, bitmap); } static BOOL update_gdi_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cacheBitmapV3) { rdpBitmap* bitmap; rdpBitmap* prevBitmap; BOOL compressed = TRUE; rdpCache* cache = context->cache; rdpSettings* settings = context->settings; BITMAP_DATA_EX* bitmapData = &cacheBitmapV3->bitmapData; bitmap = Bitmap_Alloc(context); if (!bitmap) return FALSE; if (!cacheBitmapV3->bpp) cacheBitmapV3->bpp = settings->ColorDepth; compressed = (bitmapData->codecID != RDP_CODEC_ID_NONE); Bitmap_SetDimensions(bitmap, bitmapData->width, bitmapData->height); if (!bitmap->Decompress(context, bitmap, bitmapData->data, bitmapData->width, bitmapData->height, bitmapData->bpp, bitmapData->length, compressed, bitmapData->codecID)) { Bitmap_Free(context, bitmap); return FALSE; } if (!bitmap->New(context, bitmap)) { Bitmap_Free(context, bitmap); return FALSE; } prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmapV3->cacheId, cacheBitmapV3->cacheIndex); Bitmap_Free(context, prevBitmap); return bitmap_cache_put(cache->bitmap, cacheBitmapV3->cacheId, cacheBitmapV3->cacheIndex, bitmap); } rdpBitmap* bitmap_cache_get(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index) { rdpBitmap* bitmap; if (id > bitmapCache->maxCells) { WLog_ERR(TAG, "get invalid bitmap cell id: %" PRIu32 "", id); return NULL; } if (index == BITMAP_CACHE_WAITING_LIST_INDEX) { index = bitmapCache->cells[id].number; } else if (index > bitmapCache->cells[id].number) { WLog_ERR(TAG, "get invalid bitmap index %" PRIu32 " in cell id: %" PRIu32 "", index, id); return NULL; } bitmap = bitmapCache->cells[id].entries[index]; return bitmap; } BOOL bitmap_cache_put(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index, rdpBitmap* bitmap) { if (id > bitmapCache->maxCells) { WLog_ERR(TAG, "put invalid bitmap cell id: %" PRIu32 "", id); return FALSE; } if (index == BITMAP_CACHE_WAITING_LIST_INDEX) { index = bitmapCache->cells[id].number; } else if (index > bitmapCache->cells[id].number) { WLog_ERR(TAG, "put invalid bitmap index %" PRIu32 " in cell id: %" PRIu32 "", index, id); return FALSE; } bitmapCache->cells[id].entries[index] = bitmap; return TRUE; } void bitmap_cache_register_callbacks(rdpUpdate* update) { rdpCache* cache = update->context->cache; cache->bitmap->MemBlt = update->primary->MemBlt; cache->bitmap->Mem3Blt = update->primary->Mem3Blt; update->primary->MemBlt = update_gdi_memblt; update->primary->Mem3Blt = update_gdi_mem3blt; update->secondary->CacheBitmap = update_gdi_cache_bitmap; update->secondary->CacheBitmapV2 = update_gdi_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_gdi_cache_bitmap_v3; update->BitmapUpdate = gdi_bitmap_update; } rdpBitmapCache* bitmap_cache_new(rdpSettings* settings) { int i; rdpBitmapCache* bitmapCache; bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache)); if (!bitmapCache) return NULL; bitmapCache->settings = settings; bitmapCache->update = ((freerdp*)settings->instance)->update; bitmapCache->context = bitmapCache->update->context; bitmapCache->cells = (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL)); if (!bitmapCache->cells) goto fail; bitmapCache->maxCells = settings->BitmapCacheV2NumCells; for (i = 0; i < (int)bitmapCache->maxCells; i++) { bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries; /* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */ bitmapCache->cells[i].entries = (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*)); if (!bitmapCache->cells[i].entries) goto fail; } return bitmapCache; fail: if (bitmapCache->cells) { for (i = 0; i < (int)bitmapCache->maxCells; i++) free(bitmapCache->cells[i].entries); } free(bitmapCache); return NULL; } void bitmap_cache_free(rdpBitmapCache* bitmapCache) { int i, j; rdpBitmap* bitmap; if (bitmapCache) { for (i = 0; i < (int)bitmapCache->maxCells; i++) { for (j = 0; j < (int)bitmapCache->cells[i].number + 1; j++) { bitmap = bitmapCache->cells[i].entries[j]; Bitmap_Free(bitmapCache->context, bitmap); } free(bitmapCache->cells[i].entries); } free(bitmapCache->cells); free(bitmapCache); } } static void free_bitmap_data(BITMAP_DATA* data, size_t count) { size_t x; if (!data) return; for (x = 0; x < count; x++) free(data[x].bitmapDataStream); free(data); } static BITMAP_DATA* copy_bitmap_data(const BITMAP_DATA* data, size_t count) { size_t x; BITMAP_DATA* dst = (BITMAP_DATA*)calloc(count, sizeof(BITMAP_DATA)); if (!dst) goto fail; for (x = 0; x < count; x++) { dst[x] = data[x]; if (data[x].bitmapLength > 0) { dst[x].bitmapDataStream = malloc(data[x].bitmapLength); if (!dst[x].bitmapDataStream) goto fail; memcpy(dst[x].bitmapDataStream, data[x].bitmapDataStream, data[x].bitmapLength); } } return dst; fail: free_bitmap_data(dst, count); return NULL; } void free_bitmap_update(rdpContext* context, BITMAP_UPDATE* pointer) { if (!pointer) return; free_bitmap_data(pointer->rectangles, pointer->number); free(pointer); } BITMAP_UPDATE* copy_bitmap_update(rdpContext* context, const BITMAP_UPDATE* pointer) { BITMAP_UPDATE* dst = calloc(1, sizeof(BITMAP_UPDATE)); if (!dst || !pointer) goto fail; *dst = *pointer; dst->rectangles = copy_bitmap_data(pointer->rectangles, pointer->number); if (!dst->rectangles) goto fail; return dst; fail: free_bitmap_update(context, dst); return NULL; } CACHE_BITMAP_ORDER* copy_cache_bitmap_order(rdpContext* context, const CACHE_BITMAP_ORDER* order) { CACHE_BITMAP_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_ORDER)); if (!dst || !order) goto fail; *dst = *order; if (order->bitmapLength > 0) { dst->bitmapDataStream = malloc(order->bitmapLength); if (!dst->bitmapDataStream) goto fail; memcpy(dst->bitmapDataStream, order->bitmapDataStream, order->bitmapLength); } return dst; fail: free_cache_bitmap_order(context, dst); return NULL; } void free_cache_bitmap_order(rdpContext* context, CACHE_BITMAP_ORDER* order) { if (order) free(order->bitmapDataStream); free(order); } CACHE_BITMAP_V2_ORDER* copy_cache_bitmap_v2_order(rdpContext* context, const CACHE_BITMAP_V2_ORDER* order) { CACHE_BITMAP_V2_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); if (!dst || !order) goto fail; *dst = *order; if (order->bitmapLength > 0) { dst->bitmapDataStream = malloc(order->bitmapLength); if (!dst->bitmapDataStream) goto fail; memcpy(dst->bitmapDataStream, order->bitmapDataStream, order->bitmapLength); } return dst; fail: free_cache_bitmap_v2_order(context, dst); return NULL; } void free_cache_bitmap_v2_order(rdpContext* context, CACHE_BITMAP_V2_ORDER* order) { if (order) free(order->bitmapDataStream); free(order); } CACHE_BITMAP_V3_ORDER* copy_cache_bitmap_v3_order(rdpContext* context, const CACHE_BITMAP_V3_ORDER* order) { CACHE_BITMAP_V3_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER)); if (!dst || !order) goto fail; *dst = *order; if (order->bitmapData.length > 0) { dst->bitmapData.data = malloc(order->bitmapData.length); if (!dst->bitmapData.data) goto fail; memcpy(dst->bitmapData.data, order->bitmapData.data, order->bitmapData.length); } return dst; fail: free_cache_bitmap_v3_order(context, dst); return NULL; } void free_cache_bitmap_v3_order(rdpContext* context, CACHE_BITMAP_V3_ORDER* order) { if (order) free(order->bitmapData.data); free(order); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3956_0
crossvul-cpp_data_bad_2946_0
#ifndef IGNOREALL /* dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net This is a command-line ANSI C program to convert raw photos from any digital camera on any computer running any operating system. No license is required to download and use dcraw.c. However, to lawfully redistribute dcraw, you must either (a) offer, at no extra charge, full source code* for all executable files containing RESTRICTED functions, (b) distribute this code under the GPL Version 2 or later, (c) remove all RESTRICTED functions, re-implement them, or copy them from an earlier, unrestricted Revision of dcraw.c, or (d) purchase a license from the author. The functions that process Foveon images have been RESTRICTED since Revision 1.237. All other code remains free for all uses. *If you have not modified dcraw.c in any way, a link to my homepage qualifies as "full source code". $Revision: 1.476 $ $Date: 2015/05/25 02:29:14 $ */ /*@out DEFINES #ifndef USE_JPEG #define NO_JPEG #endif #ifndef USE_JASPER #define NO_JASPER #endif @end DEFINES */ #define NO_LCMS #define DCRAW_VERBOSE //@out DEFINES #define DCRAW_VERSION "9.26" #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define _USE_MATH_DEFINES #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <float.h> #include <limits.h> #include <math.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> //@end DEFINES #if defined(DJGPP) || defined(__MINGW32__) #define fseeko fseek #define ftello ftell #else #define fgetc getc_unlocked #endif //@out DEFINES #ifdef __CYGWIN__ #include <io.h> #endif #if defined WIN32 || defined(__MINGW32__) #include <sys/utime.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define snprintf _snprintf #define strcasecmp stricmp #define strncasecmp strnicmp //@end DEFINES typedef __int64 INT64; typedef unsigned __int64 UINT64; //@out DEFINES #else #include <unistd.h> #include <utime.h> #include <netinet/in.h> typedef long long INT64; typedef unsigned long long UINT64; #endif #ifdef NODEPS #define NO_JASPER #define NO_JPEG #define NO_LCMS #endif #ifndef NO_JASPER #include <jasper/jasper.h> /* Decode Red camera movies */ #endif #ifndef NO_JPEG #include <jpeglib.h> /* Decode compressed Kodak DC120 photos */ #endif /* and Adobe Lossy DNGs */ #ifndef NO_LCMS #ifdef USE_LCMS #include <lcms.h> /* Support color profiles */ #else #include <lcms2.h> /* Support color profiles */ #endif #endif #ifdef LOCALEDIR #include <libintl.h> #define _(String) gettext(String) #else #define _(String) (String) #endif #ifdef LJPEG_DECODE #error Please compile dcraw.c by itself. #error Do not link it with ljpeg_decode. #endif #ifndef LONG_BIT #define LONG_BIT (8 * sizeof(long)) #endif //@end DEFINES #if !defined(uchar) #define uchar unsigned char #endif #if !defined(ushort) #define ushort unsigned short #endif /* All global variables are defined here, and all functions that access them are prefixed with "CLASS". Note that a thread-safe C++ class cannot have non-const static local variables. */ FILE *ifp, *ofp; short order; const char *ifname; char *meta_data, xtrans[6][6], xtrans_abs[6][6]; char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64], software[64]; float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len; time_t timestamp; off_t strip_offset, data_offset; off_t thumb_offset, meta_offset, profile_offset; unsigned shot_order, kodak_cbpp, exif_cfa, unique_id; unsigned thumb_length, meta_length, profile_length; unsigned thumb_misc, *oprof, fuji_layout, shot_select = 0, multi_out = 0; unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress; unsigned black, maximum, mix_green, raw_color, zero_is_bad; unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error; unsigned tile_width, tile_length, gpsdata[32], load_flags; unsigned flip, tiff_flip, filters, colors; ushort raw_height, raw_width, height, width, top_margin, left_margin; ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height; ushort *raw_image, (*image)[4], cblack[4102]; ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4]; double pixel_aspect, aber[4] = {1, 1, 1, 1}, gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; float bright = 1, user_mul[4] = {0, 0, 0, 0}, threshold = 0; int mask[8][4]; int half_size = 0, four_color_rgb = 0, document_mode = 0, highlight = 0; int verbose = 0, use_auto_wb = 0, use_camera_wb = 0, use_camera_matrix = 1; int output_color = 1, output_bps = 8, output_tiff = 0, med_passes = 0; int no_auto_bright = 0; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4]; const double xyz_rgb[3][3] = {/* XYZ from RGB */ {0.412453, 0.357580, 0.180423}, {0.212671, 0.715160, 0.072169}, {0.019334, 0.119193, 0.950227}}; const float d65_white[3] = {0.950456, 1, 1.088754}; int histogram[4][0x2000]; void (*write_thumb)(), (*write_fun)(); void (*load_raw)(), (*thumb_load_raw)(); jmp_buf failure; struct decode { struct decode *branch[2]; int leaf; } first_decode[2048], *second_decode, *free_decode; struct tiff_ifd { int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes; int t_tile_width, t_tile_length, sample_format, predictor; float t_shutter; } tiff_ifd[10]; struct ph1 { int format, key_off, tag_21a; int t_black, split_col, black_col, split_row, black_row; float tag_210; } ph1; #define CLASS //@out DEFINES #define FORC(cnt) for (c = 0; c < cnt; c++) #define FORC3 FORC(3) #define FORC4 FORC(4) #define FORCC for (c = 0; c < colors && c < 4; c++) #define SQR(x) ((x) * (x)) #define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM((int)(x), 0, 65535) #define CLIP15(x) LIM((int)(x), 0, 32767) #define SWAP(a, b) \ { \ a = a + b; \ b = a - b; \ a = a - b; \ } #define my_swap(type, i, j) \ { \ type t = i; \ i = j; \ j = t; \ } static float fMAX(float a, float b) { return MAX(a, b); } /* In order to inline this calculation, I make the risky assumption that all filter patterns can be described by a repeating pattern of eight rows and two columns Do not use the FC or BAYER macros with the Leaf CatchLight, because its pattern is 16x16, not 2x8. Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2 PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1 0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M 1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C 2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y 3 C Y C Y C Y 3 G M G M G M 3 G M G M G M 4 C Y C Y C Y 4 Y C Y C Y C PowerShot A5 5 G M G M G M 5 G M G M G M 0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y 7 M G M G M G 7 M G M G M G 0 1 2 3 4 5 0 C Y C Y C Y 1 G M G M G M 2 C Y C Y C Y 3 M G M G M G All RGB cameras use one of these Bayer grids: 0x16161616: 0x61616161: 0x49494949: 0x94949494: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G 1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B 2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G 3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B */ #define RAW(row, col) raw_image[(row)*raw_width + (col)] //@end DEFINES #define FC(row, col) (filters >> ((((row) << 1 & 14) + ((col)&1)) << 1) & 3) //@out DEFINES #define BAYER(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][FC(row, col)] #define BAYER2(row, col) image[((row) >> shrink) * iwidth + ((col) >> shrink)][fcol(row, col)] //@end DEFINES /* @out COMMON #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end COMMON */ //@out COMMON int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) //@end COMMON void CLASS merror(void *ptr, const char *where) { if (ptr) return; fprintf(stderr, _("%s: Out of memory in %s\n"), ifname, where); longjmp(failure, 1); } void CLASS derror() { if (!data_error) { fprintf(stderr, "%s: ", ifname); if (feof(ifp)) fprintf(stderr, _("Unexpected end of file\n")); else fprintf(stderr, _("Corrupt data near 0x%llx\n"), (INT64)ftello(ifp)); } data_error++; } //@out COMMON ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, int count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } //@end COMMON struct jhead { int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6]; ushort quant[64], idct[64], *huff[20], *free[20], *row; }; //@out COMMON int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD if (row < raw_height && col < raw_width) FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width * 3 * tiff_bps / 8; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } //@end COMMON void CLASS jpeg_thumb(); //@out COMMON void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS panasonic_16x10_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_DECODE_RAW; #endif } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* 264 looks enough */ int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx < 0xffff) { if ((RAW(row, col + i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } //@end COMMON /* RESTRICTED code starts here */ void CLASS foveon_decoder(unsigned size, unsigned code) { static unsigned huff[1024]; struct decode *cur; int i, len; if (!code) { for (i = 0; i < size; i++) huff[i] = get4(); memset(first_decode, 0, sizeof first_decode); free_decode = first_decode; } cur = free_decode++; if (free_decode > first_decode + 2048) { fprintf(stderr, _("%s: decoder table overflow\n"), ifname); longjmp(failure, 2); } if (code) for (i = 0; i < size; i++) if (huff[i] == code) { cur->leaf = i; return; } if ((len = code >> 27) > 26) return; code = (len + 1) << 27 | (code & 0x3ffffff) << 1; cur->branch[0] = free_decode; foveon_decoder(size, code); cur->branch[1] = free_decode; foveon_decoder(size, code + 1); } void CLASS foveon_thumb() { unsigned bwide, row, col, bitbuf = 0, bit = 1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width * 3) return; buf = (char *)malloc(bwide); merror(buf, "foveon_thumb()"); for (row = 0; row < thumb_height; row++) { fread(buf, 1, bwide, ifp); fwrite(buf, 3, thumb_width, ofp); } free(buf); return; } foveon_decoder(256, 0); for (row = 0; row < thumb_height; row++) { memset(pred, 0, sizeof pred); if (!bit) get4(); for (bit = col = 0; col < thumb_width; col++) FORC3 { for (dindex = first_decode; dindex->branch[0];) { if ((bit = (bit - 1) & 31) == 31) for (i = 0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc(pred[c], ofp); } } } void CLASS foveon_sd_load_raw() { struct decode *dindex; short diff[1024]; unsigned bitbuf = 0; int pred[3], row, col, bit = -1, c, i; read_shorts((ushort *)diff, 1024); if (!load_flags) foveon_decoder(1024, 0); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(pred, 0, sizeof pred); if (!bit && !load_flags && atoi(model + 2) < 14) get4(); for (col = bit = 0; col < width; col++) { if (load_flags) { bitbuf = get4(); FORC3 pred[2 - c] += diff[bitbuf >> c * 10 & 0x3ff]; } else FORC3 { for (dindex = first_decode; dindex->branch[0];) { if ((bit = (bit - 1) & 31) == 31) for (i = 0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += diff[dindex->leaf]; if (pred[c] >> 16 && ~pred[c] >> 16) derror(); } FORC3 image[row * width + col][c] = pred[c]; } } } void CLASS foveon_huff(ushort *huff) { int i, j, clen, code; huff[0] = 8; for (i = 0; i < 13; i++) { clen = getc(ifp); code = getc(ifp); for (j = 0; j<256>> clen;) huff[code + ++j] = clen << 8 | i; } get2(); } void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[512], vpred[2][2], hpred[2]; fseek(ifp, 8, SEEK_CUR); foveon_huff(huff); roff[0] = 48; FORC3 roff[c + 1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek(ifp, data_offset + roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row * width + col][c] = hpred[col & 1]; } } } } void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512, 512}, {512, 512}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread(meta_data, 1, meta_length, ifp); for (i = 0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64)301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free(meta_data); meta_data = (char *)malloc(meta_length = wide * high * 3 / 2); merror(meta_data, "foveon_load_camf()"); foveon_huff(huff); get4(); getbits(-1); for (j = row = 0; row < high; row++) { for (col = 0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } #ifdef DCRAW_VERBOSE else fprintf(stderr, _("%s has unknown CAMF type %d.\n"), ifname, type); #endif } const char *CLASS foveon_camf_param(const char *block, const char *param) { unsigned idx, num; char *pos, *cp, *dp; for (idx = 0; idx < meta_length; idx += sget4(pos + 8)) { pos = meta_data + idx; if (strncmp(pos, "CMb", 3)) break; if (pos[3] != 'P') continue; if (strcmp(block, pos + sget4(pos + 12))) continue; cp = pos + sget4(pos + 16); num = sget4(cp); dp = pos + sget4(cp + 4); while (num--) { cp += 8; if (!strcmp(param, dp + sget4(cp))) return dp + sget4(cp + 4); } } return 0; } void *CLASS foveon_camf_matrix(unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx = 0; idx < meta_length; idx += sget4(pos + 8)) { pos = meta_data + idx; if (strncmp(pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp(name, pos + sget4(pos + 12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos + 16); type = sget4(cp); if ((ndim = sget4(cp + 4)) > 3) break; dp = pos + sget4(cp + 8); for (i = ndim; i--;) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double)dim[0] * dim[1] * dim[2]) > meta_length / 4) break; mat = (unsigned *)malloc((size = dsize) * 4); merror(mat, "foveon_camf_matrix()"); for (i = 0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i * 4); else mat[i] = sget4(dp + i * 2) & 0xffff; return mat; } #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: \"%s\" matrix not found!\n"), ifname, name); #endif return 0; } int CLASS foveon_fixed(void *ptr, int size, const char *name) { void *dp; unsigned dim[3]; if (!name) return 0; dp = foveon_camf_matrix(dim, name); if (!dp) return 0; memcpy(ptr, dp, size * 4); free(dp); return 1; } float CLASS foveon_avg(short *pix, int range[2], float cfilt) { int i; float val, min = FLT_MAX, max = -FLT_MAX, sum = 0; for (i = range[0]; i <= range[1]; i++) { sum += val = pix[i * 4] + (pix[i * 4] - pix[(i - 1) * 4]) * cfilt; if (min > val) min = val; if (max < val) max = val; } if (range[1] - range[0] == 1) return sum / 2; return (sum - min - max) / (range[1] - range[0] - 1); } short *CLASS foveon_make_curve(double max, double mul, double filt) { short *curve; unsigned i, size; double x; if (!filt) filt = 0.8; size = 4 * M_PI * max / filt; if (size == UINT_MAX) size--; curve = (short *)calloc(size + 1, sizeof *curve); merror(curve, "foveon_make_curve()"); curve[0] = size; for (i = 0; i < size; i++) { x = i * filt / max / 4; curve[i + 1] = (cos(x) + 1) / 2 * tanh(i * filt / mul) * mul + 0.5; } return curve; } void CLASS foveon_make_curves(short **curvep, float dq[3], float div[3], float filt) { double mul[3], max = 0; int c; FORC3 mul[c] = dq[c] / div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve(max, mul[c], filt); } int CLASS foveon_apply_curve(short *curve, int i) { if (abs(i) >= curve[0]) return 0; return i < 0 ? -curve[1 - i] : curve[1 + i]; } #define image ((short(*)[4])image) void CLASS foveon_interpolate() { static const short hood[] = {-1, -1, -1, 0, -1, 1, 0, -1, 0, 1, 1, -1, 1, 0, 1, 1}; short *pix, prev[3], *curve[8], (*shrink)[3]; float cfilt = 0, ddft[3][3][2], ppm[3][3][3]; float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3]; float chroma_dq[3], color_dq[3], diag[3][3], div[3]; float(*black)[3], (*sgain)[3], (*sgrow)[3]; float fsum[3], val, frow, num; int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit; int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3]; int work[3][3], smlast, smred, smred_p = 0, dev[3]; int satlev[3], keep[4], active[4]; unsigned dim[3], *badpix; double dsum = 0, trsum[3]; char str[128]; const char *cp; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Foveon interpolation...\n")); #endif foveon_load_camf(); foveon_fixed(dscr, 4, "DarkShieldColRange"); foveon_fixed(ppm[0][0], 27, "PostPolyMatrix"); foveon_fixed(satlev, 3, "SaturationLevel"); foveon_fixed(keep, 4, "KeepImageArea"); foveon_fixed(active, 4, "ActiveImageArea"); foveon_fixed(chroma_dq, 3, "ChromaDQ"); foveon_fixed(color_dq, 3, foveon_camf_param("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB"); if (foveon_camf_param("IncludeBlocks", "ColumnFilter")) foveon_fixed(&cfilt, 1, "ColumnFilter"); memset(ddft, 0, sizeof ddft); if (!foveon_camf_param("IncludeBlocks", "DarkDrift") || !foveon_fixed(ddft[1][0], 12, "DarkDrift")) for (i = 0; i < 2; i++) { foveon_fixed(dstb, 4, i ? "DarkShieldBottom" : "DarkShieldTop"); for (row = dstb[1]; row <= dstb[3]; row++) for (col = dstb[0]; col <= dstb[2]; col++) FORC3 ddft[i + 1][c][1] += (short)image[row * width + col][c]; FORC3 ddft[i + 1][c][1] /= (dstb[3] - dstb[1] + 1) * (dstb[2] - dstb[0] + 1); } if (!(cp = foveon_camf_param("WhiteBalanceIlluminants", model2))) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Invalid white balance \"%s\"\n"), ifname, model2); #endif return; } foveon_fixed(cam_xyz, 9, cp); foveon_fixed(correct, 9, foveon_camf_param("WhiteBalanceCorrections", model2)); memset(last, 0, sizeof last); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j]; #define LAST(x, y) last[(i + x) % 3][(c + y) % 3] for (i = 0; i < 3; i++) FORC3 diag[c][i] = LAST(1, 1) * LAST(2, 2) - LAST(1, 2) * LAST(2, 1); #undef LAST FORC3 div[c] = diag[c][0] * 0.3127 + diag[c][1] * 0.329 + diag[c][2] * 0.3583; sprintf(str, "%sRGBNeutral", model2); if (foveon_camf_param("IncludeBlocks", str)) foveon_fixed(div, 3, str); num = 0; FORC3 if (num < div[c]) num = div[c]; FORC3 div[c] /= num; memset(trans, 0, sizeof trans); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j]; FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2]; dsum = (6 * trsum[0] + 11 * trsum[1] + 3 * trsum[2]) / 20; for (i = 0; i < 3; i++) FORC3 last[i][c] = trans[i][c] * dsum / trsum[i]; memset(trans, 0, sizeof trans); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) FORC3 trans[i][j] += (i == c ? 32 : -1) * last[c][j] / 30; foveon_make_curves(curve, color_dq, div, cfilt); FORC3 chroma_dq[c] /= 3; foveon_make_curves(curve + 3, chroma_dq, div, cfilt); FORC3 dsum += chroma_dq[c] / div[c]; curve[6] = foveon_make_curve(dsum, dsum, cfilt); curve[7] = foveon_make_curve(dsum * 2, dsum * 2, cfilt); sgain = (float(*)[3])foveon_camf_matrix(dim, "SpatialGain"); if (!sgain) return; sgrow = (float(*)[3])calloc(dim[1], sizeof *sgrow); sgx = (width + dim[1] - 2) / (dim[1] - 1); black = (float(*)[3])calloc(height, sizeof *black); for (row = 0; row < height; row++) { for (i = 0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); FORC3 black[row][c] = (foveon_avg(image[row * width] + c, dscr[0], cfilt) + foveon_avg(image[row * width] + c, dscr[1], cfilt) * 3 - ddft[0][c][0]) / 4 - ddft[0][c][1]; } memcpy(black, black + 8, sizeof *black * 8); memcpy(black + height - 11, black + height - 22, 11 * sizeof *black); memcpy(last, black, sizeof last); for (row = 1; row < height - 1; row++) { FORC3 if (last[1][c] > last[0][c]) { if (last[1][c] > last[2][c]) black[row][c] = (last[0][c] > last[2][c]) ? last[0][c] : last[2][c]; } else if (last[1][c] < last[2][c]) black[row][c] = (last[0][c] < last[2][c]) ? last[0][c] : last[2][c]; memmove(last, last + 1, 2 * sizeof last[0]); memcpy(last[2], black[row + 1], sizeof last[2]); } FORC3 black[row][c] = (last[0][c] + last[1][c]) / 2; FORC3 black[0][c] = (black[1][c] + black[3][c]) / 2; val = 1 - exp(-1 / 24.0); memcpy(fsum, black, sizeof fsum); for (row = 1; row < height; row++) FORC3 fsum[c] += black[row][c] = (black[row][c] - black[row - 1][c]) * val + black[row - 1][c]; memcpy(last[0], black[height - 1], sizeof last[0]); FORC3 fsum[c] /= height; for (row = height; row--;) FORC3 last[0][c] = black[row][c] = (black[row][c] - fsum[c] - last[0][c]) * val + last[0][c]; memset(total, 0, sizeof total); for (row = 2; row < height; row += 4) for (col = 2; col < width; col += 4) { FORC3 total[c] += (short)image[row * width + col][c]; total[3]++; } for (row = 0; row < height; row++) FORC3 black[row][c] += fsum[c] / 2 + total[c] / (total[3] * 100.0); for (row = 0; row < height; row++) { for (i = 0; i < 6; i++) ((float *)ddft[0])[i] = ((float *)ddft[1])[i] + row / (height - 1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]); pix = image[row * width]; memcpy(prev, pix, sizeof prev); frow = row / (height - 1.0) * (dim[2] - 1); if ((irow = frow) == dim[2] - 1) irow--; frow -= irow; for (i = 0; i < dim[1]; i++) FORC3 sgrow[i][c] = sgain[irow * dim[1] + i][c] * (1 - frow) + sgain[(irow + 1) * dim[1] + i][c] * frow; for (col = 0; col < width; col++) { FORC3 { diff = pix[c] - prev[c]; prev[c] = pix[c]; ipix[c] = pix[c] + floor((diff + (diff * diff >> 14)) * cfilt - ddft[0][c][1] - ddft[0][c][0] * ((float)col / width - 0.5) - black[row][c]); } FORC3 { work[0][c] = ipix[c] * ipix[c] >> 14; work[2][c] = ipix[c] * work[0][c] >> 14; work[1][2 - c] = ipix[(c + 1) % 3] * ipix[(c + 2) % 3] >> 14; } FORC3 { for (val = i = 0; i < 3; i++) for (j = 0; j < 3; j++) val += ppm[c][i][j] * work[i][j]; ipix[c] = floor((ipix[c] + floor(val)) * (sgrow[col / sgx][c] * (sgx - col % sgx) + sgrow[col / sgx + 1][c] * (col % sgx)) / sgx / div[c]); if (ipix[c] > 32000) ipix[c] = 32000; pix[c] = ipix[c]; } pix += 4; } } free(black); free(sgrow); free(sgain); if ((badpix = (unsigned *)foveon_camf_matrix(dim, "BadPixels"))) { for (i = 0; i < dim[0]; i++) { col = (badpix[i] >> 8 & 0xfff) - keep[0]; row = (badpix[i] >> 20) - keep[1]; if ((unsigned)(row - 1) > height - 3 || (unsigned)(col - 1) > width - 3) continue; memset(fsum, 0, sizeof fsum); for (sum = j = 0; j < 8; j++) if (badpix[i] & (1 << j)) { FORC3 fsum[c] += (short)image[(row + hood[j * 2]) * width + col + hood[j * 2 + 1]][c]; sum++; } if (sum) FORC3 image[row * width + col][c] = fsum[c] / sum; } free(badpix); } /* Array for 5x5 Gaussian averaging of red values */ smrow[6] = (int(*)[3])calloc(width * 5, sizeof **smrow); merror(smrow[6], "foveon_interpolate()"); for (i = 0; i < 5; i++) smrow[i] = smrow[6] + i * width; /* Sharpen the reds against these Gaussian averages */ for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { smrow[4][col][0] = (pix[0] * 6 + (pix[-4] + pix[4]) * 4 + pix[-8] + pix[8] + 8) >> 4; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { smred = (6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] + 8) >> 4; if (col == 2) smred_p = smred; i = pix[0] + ((pix[0] - ((smred * 7 + smred_p) >> 3)) >> 3); if (i > 32000) i = 32000; pix[0] = i; smred_p = smred; pix += 4; } } /* Adjust the brighter pixels for better linearity */ min = 0xffff; FORC3 { i = satlev[c] / div[c]; if (min > i) min = i; } limit = min * 9 >> 4; for (pix = image[0]; pix < image[height * width]; pix += 4) { if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit) continue; min = max = pix[0]; for (c = 1; c < 3; c++) { if (min > pix[c]) min = pix[c]; if (max < pix[c]) max = pix[c]; } if (min >= limit * 2) { pix[0] = pix[1] = pix[2] = max; } else { i = 0x4000 - ((min - limit) << 14) / limit; i = 0x4000 - (i * i >> 14); i = i * i >> 14; FORC3 pix[c] += (max - pix[c]) * i >> 14; } } /* Because photons that miss one detector often hit another, the sum R+G+B is much less noisy than the individual colors. So smooth the hues without smoothing the total. */ for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 smrow[4][col][c] = (pix[c - 4] + 2 * pix[c] + pix[c + 4] + 2) >> 2; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 dev[c] = -foveon_apply_curve(curve[7], pix[c] - ((smrow[1][col][c] + 2 * smrow[2][col][c] + smrow[3][col][c]) >> 2)); sum = (dev[0] + dev[1] + dev[2]) >> 3; FORC3 pix[c] += dev[c] - sum; pix += 4; } } for (smlast = -1, row = 2; row < height - 2; row++) { while (smlast < row + 2) { for (i = 0; i < 6; i++) smrow[(i + 5) % 6] = smrow[i]; pix = image[++smlast * width + 2]; for (col = 2; col < width - 2; col++) { FORC3 smrow[4][col][c] = (pix[c - 8] + pix[c - 4] + pix[c] + pix[c + 4] + pix[c + 8] + 2) >> 2; pix += 4; } } pix = image[row * width + 2]; for (col = 2; col < width - 2; col++) { for (total[3] = 375, sum = 60, c = 0; c < 3; c++) { for (total[c] = i = 0; i < 5; i++) total[c] += smrow[i][col][c]; total[3] += total[c]; sum += pix[c]; } if (sum < 0) sum = 0; j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174; FORC3 pix[c] += foveon_apply_curve(curve[6], ((j * total[c] + 0x8000) >> 16) - pix[c]); pix += 4; } } /* Transform the image to a different colorspace */ for (pix = image[0]; pix < image[height * width]; pix += 4) { FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c]); sum = (pix[0] + pix[1] + pix[1] + pix[2]) >> 2; FORC3 pix[c] -= foveon_apply_curve(curve[c], pix[c] - sum); FORC3 { for (dsum = i = 0; i < 3; i++) dsum += trans[c][i] * pix[i]; if (dsum < 0) dsum = 0; if (dsum > 24000) dsum = 24000; ipix[c] = dsum + 0.5; } FORC3 pix[c] = ipix[c]; } /* Smooth the image bottom-to-top and save at 1/4 scale */ shrink = (short(*)[3])calloc((height / 4), (width / 4) * sizeof *shrink); merror(shrink, "foveon_interpolate()"); for (row = height / 4; row--;) for (col = 0; col < width / 4; col++) { ipix[0] = ipix[1] = ipix[2] = 0; for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) FORC3 ipix[c] += image[(row * 4 + i) * width + col * 4 + j][c]; FORC3 if (row + 2 > height / 4) shrink[row * (width / 4) + col][c] = ipix[c] >> 4; else shrink[row * (width / 4) + col][c] = (shrink[(row + 1) * (width / 4) + col][c] * 1840 + ipix[c] * 141 + 2048) >> 12; } /* From the 1/4-scale image, smooth right-to-left */ for (row = 0; row < (height & ~3); row++) { ipix[0] = ipix[1] = ipix[2] = 0; if ((row & 3) == 0) for (col = width & ~3; col--;) FORC3 smrow[0][col][c] = ipix[c] = (shrink[(row / 4) * (width / 4) + col / 4][c] * 1485 + ipix[c] * 6707 + 4096) >> 13; /* Then smooth left-to-right */ ipix[0] = ipix[1] = ipix[2] = 0; for (col = 0; col < (width & ~3); col++) FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c] * 1485 + ipix[c] * 6707 + 4096) >> 13; /* Smooth top-to-bottom */ if (row == 0) memcpy(smrow[2], smrow[1], sizeof **smrow * width); else for (col = 0; col < (width & ~3); col++) FORC3 smrow[2][col][c] = (smrow[2][col][c] * 6707 + smrow[1][col][c] * 1485 + 4096) >> 13; /* Adjust the chroma toward the smooth values */ for (col = 0; col < (width & ~3); col++) { for (i = j = 30, c = 0; c < 3; c++) { i += smrow[2][col][c]; j += image[row * width + col][c]; } j = (j << 16) / i; for (sum = c = 0; c < 3; c++) { ipix[c] = foveon_apply_curve(curve[c + 3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row * width + col][c]); sum += ipix[c]; } sum >>= 3; FORC3 { i = image[row * width + col][c] + ipix[c] - sum; if (i < 0) i = 0; image[row * width + col][c] = i; } } } free(shrink); free(smrow[6]); for (i = 0; i < 8; i++) free(curve[i]); /* Trim off the black border */ active[1] -= keep[1]; active[3] -= 2; i = active[2] - active[0]; for (row = 0; row < active[3] - active[1]; row++) memcpy(image[row * i], image[(row + active[1]) * width + active[0]], i * sizeof *image); width = i; height = row; } #undef image /* RESTRICTED code ends here */ //@out COMMON void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } //@end COMMON /* @out FILEIO #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" @end FILEIO */ // @out FILEIO /* Seach from the current directory up to the root looking for a ".badpixels" file, and fix those pixels now. */ void CLASS bad_pixels(const char *cfname) { FILE *fp = NULL; #ifndef LIBRAW_LIBRARY_BUILD char *fname, *cp, line[128]; int len, time, row, col, r, c, rad, tot, n, fixed = 0; #else char *cp, line[128]; int time, row, col, r, c, rad, tot, n; #ifdef DCRAW_VERBOSE int fixed = 0; #endif #endif if (!filters) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 0, 2); #endif if (cfname) fp = fopen(cfname, "r"); // @end FILEIO else { for (len = 32;; len *= 2) { fname = (char *)malloc(len); if (!fname) return; if (getcwd(fname, len - 16)) break; free(fname); if (errno != ERANGE) return; } #if defined(WIN32) || defined(DJGPP) if (fname[1] == ':') memmove(fname, fname + 2, len - 2); for (cp = fname; *cp; cp++) if (*cp == '\\') *cp = '/'; #endif cp = fname + strlen(fname); if (cp[-1] == '/') cp--; while (*fname == '/') { strcpy(cp, "/.badpixels"); if ((fp = fopen(fname, "r"))) break; if (cp == fname) break; while (*--cp != '/') ; } free(fname); } // @out FILEIO if (!fp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP; #endif return; } while (fgets(line, 128, fp)) { cp = strchr(line, '#'); if (cp) *cp = 0; if (sscanf(line, "%d %d %d", &col, &row, &time) != 3) continue; if ((unsigned)col >= width || (unsigned)row >= height) continue; if (time > timestamp) continue; for (tot = n = 0, rad = 1; rad < 3 && n == 0; rad++) for (r = row - rad; r <= row + rad; r++) for (c = col - rad; c <= col + rad; c++) if ((unsigned)r < height && (unsigned)c < width && (r != row || c != col) && fcol(r, c) == fcol(row, col)) { tot += BAYER2(r, c); n++; } BAYER2(row, col) = tot / n; #ifdef DCRAW_VERBOSE if (verbose) { if (!fixed++) fprintf(stderr, _("Fixed dead pixels at:")); fprintf(stderr, " %d,%d", col, row); } #endif } #ifdef DCRAW_VERBOSE if (fixed) fputc('\n', stderr); #endif fclose(fp); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS, 1, 2); #endif } void CLASS subtract(const char *fname) { FILE *fp; int dim[3] = {0, 0, 0}, comment = 0, number = 0, error = 0, nd = 0, c, row, col; ushort *pixel; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 0, 2); #endif if (!(fp = fopen(fname, "rb"))) { #ifdef DCRAW_VERBOSE perror(fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE; #endif return; } if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1; while (!error && nd < 3 && (c = fgetc(fp)) != EOF) { if (c == '#') comment = 1; if (c == '\n') comment = 0; if (comment) continue; if (isdigit(c)) number = 1; if (number) { if (isdigit(c)) dim[nd] = dim[nd] * 10 + c - '0'; else if (isspace(c)) { number = 0; nd++; } else error = 1; } } if (error || nd < 3) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s is not a valid PGM file!\n"), fname); #endif fclose(fp); return; } else if (dim[0] != width || dim[1] != height || dim[2] != 65535) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s has the wrong dimensions!\n"), fname); #endif #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM; #endif fclose(fp); return; } pixel = (ushort *)calloc(width, sizeof *pixel); merror(pixel, "subtract()"); for (row = 0; row < height; row++) { fread(pixel, 2, width, fp); for (col = 0; col < width; col++) BAYER(row, col) = MAX(BAYER(row, col) - ntohs(pixel[col]), 0); } free(pixel); fclose(fp); memset(cblack, 0, sizeof cblack); black = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME, 1, 2); #endif } //@end FILEIO //@out COMMON static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) row--; } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } //@end COMMON int CLASS parse_tiff_ifd(int base); //@out COMMON static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float powf64(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } unsigned CLASS setCanonBodyFeatures(unsigned id) { if (id == 0x03740000) // EOS M3 id = 0x80000374; else if (id == 0x03840000) // EOS M10 id = 0x80000384; else if (id == 0x03940000) // EOS M5 id = 0x80000394; else if (id == 0x04070000) // EOS M6 id = 0x80000407; else if (id == 0x03980000) // EOS M100 id = 0x80000398; imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) || // M6 (id == 0x80000398) // M100 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return id; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short CameraInfo[0] = 0; CameraInfo[1] = 0; if (type == 4) { if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) || (maxlen == 171) || (maxlen == 264) || (maxlen > 400)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-3)<<2)); else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-1)<<2)); else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-2)<<2)); else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-4)<<2)); } switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); imgdata.other.CameraTemperature = 0.0f; break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x80000398) || // M100 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000))) // G1 X Mark III for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if (id == 0x5330303638ULL) { strcpy (model, "E-M10MarkIII"); } if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 24, SEEK_CUR); tempAp = get2(); if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp-128); tempAp = get2(); if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32; get2(); // fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000) || // G1 X Mark III (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000398) || // EOS M100 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x231 << 1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 358) || // ILCE-9 (id == 362) || // ILCE-7RM3 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 358) || (id == 360) || (id == 362)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x0116(uchar *buf, unsigned id) { if ((id == 257) || (id == 262) || (id == 269) || (id == 270)) imgdata.other.BatteryTemperature = (float) (buf[1]-32) / 1.8f; else if ((id != 263) && (id != 264) && (id != 265) && (id != 266)) imgdata.other.BatteryTemperature = (float) (buf[2]-32) / 1.8f; return; } void CLASS process_Sony_0x9402(uchar *buf) { if (buf[2] != 0xff) return; short bufx = SonySubstitution[buf[0]]; if ((bufx < 0x0f) || (bufx > 0x1a) || (bufx == 0x16) || (bufx == 0x18)) return; imgdata.other.AmbientTemperature = (float) ((short) SonySubstitution[buf[4]]); return; } void CLASS process_Sony_0x9403(uchar *buf) { short bufx = SonySubstitution[buf[4]]; if ((bufx == 0x00) || (bufx == 0x94)) return; imgdata.other.SensorTemperature = (float) ((short) SonySubstitution[buf[5]]); return; } void CLASS process_Sony_0x9406(uchar *buf) { short bufx = SonySubstitution[buf[0]]; if ((bufx != 0x00) && (bufx == 0x01) && (bufx == 0x03)) return; bufx = SonySubstitution[buf[2]]; if ((bufx != 0x02) && (bufx == 0x03)) return; imgdata.other.BatteryTemperature = (float) (SonySubstitution[buf[5]]-32) / 1.8f; return; } void CLASS process_Sony_0x940c(uchar *buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050(uchar *buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_present, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_present, uchar *&table_buf_0x0116, ushort &table_buf_0x0116_present, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_present, uchar *&table_buf_0x9403, ushort &table_buf_0x9403_present, uchar *&table_buf_0x9406, ushort &table_buf_0x9406_present) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x0116_present) { process_Sony_0x0116(table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free(table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x9402_present) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } if (table_buf_0x9403_present) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } if (table_buf_0x9406_present) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x0116 && len < 256000) { table_buf_0x0116 = (uchar *)malloc(len); table_buf_0x0116_present = 1; fread(table_buf_0x0116, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x0116 (table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x9402 && len < 256000) { table_buf_0x9402 = (uchar *)malloc(len); table_buf_0x9402_present = 1; fread(table_buf_0x9402, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } } else if (tag == 0x9403 && len < 256000) { table_buf_0x9403 = (uchar *)malloc(len); table_buf_0x9403_present = 1; fread(table_buf_0x9403, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } } else if (tag == 0x9406 && len < 256000) { table_buf_0x9406 = (uchar *)malloc(len); table_buf_0x9406_present = 1; fread(table_buf_0x9406, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) continue; tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */} #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) || !strncasecmp(model, "Hasselblad A6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x003b) // all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = powf64(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; pos = strtok(ccms, ","); for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok(NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 1030) && (len == 1)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 1043) && (len == 1)) imgdata.other.SensorTemperature = getreal(type); if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif //@end COMMON void CLASS parse_minolta(int base); int CLASS parse_tiff(int base); //@out COMMON int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > fsize * 2) continue; // skip tag pointing out of 2xfile if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width * raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) load_flags = 24; if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(), get4()))); aperture = powf64(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = powf64(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD unique_id = setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0211: imgdata.other.SensorTemperature2 = int_to_float(data); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.SensorTemperature = ph1.tag_210; #endif break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } //@end COMMON char *CLASS foveon_gets(int offset, char *str, int len) { int i; fseek(ifp, offset, SEEK_SET); for (i = 0; i < len - 1; i++) if ((str[i] = get2()) == 0) break; str[i] = 0; return str; } void CLASS parse_foveon() { int entries, img = 0, off, len, tag, save, i, wide, high, pent, poff[256][2]; char name[64], value[64]; order = 0x4949; /* Little-endian */ fseek(ifp, 36, SEEK_SET); flip = get4(); fseek(ifp, -4, SEEK_END); fseek(ifp, get4(), SEEK_SET); if (get4() != 0x64434553) return; /* SECd */ entries = (get4(), get4()); while (entries--) { off = get4(); len = get4(); tag = get4(); save = ftell(ifp); fseek(ifp, off, SEEK_SET); if (get4() != (0x20434553 | (tag << 24))) return; switch (tag) { case 0x47414d49: /* IMAG */ case 0x32414d49: /* IMA2 */ fseek(ifp, 8, SEEK_CUR); pent = get4(); wide = get4(); high = get4(); if (wide > raw_width && high > raw_height) { switch (pent) { case 5: load_flags = 1; case 6: load_raw = &CLASS foveon_sd_load_raw; break; case 30: load_raw = &CLASS foveon_dp_load_raw; break; default: load_raw = 0; } raw_width = wide; raw_height = high; data_offset = off + 28; is_foveon = 1; } fseek(ifp, off + 28, SEEK_SET); if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len - 28) { thumb_offset = off + 28; thumb_length = len - 28; write_thumb = &CLASS jpeg_thumb; } if (++img == 2 && !thumb_length) { thumb_offset = off + 24; thumb_width = wide; thumb_height = high; write_thumb = &CLASS foveon_thumb; } break; case 0x464d4143: /* CAMF */ meta_offset = off + 8; meta_length = len - 28; break; case 0x504f5250: /* PROP */ pent = (get4(), get4()); fseek(ifp, 12, SEEK_CUR); off += pent * 8 + 24; if ((unsigned)pent > 256) pent = 256; for (i = 0; i < pent * 2; i++) ((int *)poff)[i] = off + get4() * 2; for (i = 0; i < pent; i++) { foveon_gets(poff[i][0], name, 64); foveon_gets(poff[i][1], value, 64); if (!strcmp(name, "ISO")) iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(make, value); if (!strcmp(name, "CAMMODEL")) strcpy(model, value); if (!strcmp(name, "WB_DESC")) strcpy(model2, value); if (!strcmp(name, "TIME")) timestamp = atoi(value); if (!strcmp(name, "EXPTIME")) shutter = atoi(value) / 1000000.0; if (!strcmp(name, "APERTURE")) aperture = atof(value); if (!strcmp(name, "FLENGTH")) focal_len = atof(value); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "IMAGERTEMP")) imgdata.other.SensorTemperature = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } #endif } #ifdef LOCALTIME timestamp = mktime(gmtime(&timestamp)); #endif } fseek(ifp, save, SEEK_SET); } } //@out COMMON /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M100", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark III", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-E3", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D850", 0, 0, { 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-G9", -15, 0, /* temp */ { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // {3984,0,0,0,10000,0,0,0,7666}}, {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */ { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */ // { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ // {2423,0,0,0,9901,0,0,0,7989}}, { 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */ { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ // { 3984,0,0,0,10000,0,0,0,7666 } }, {10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */ { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {"Sony DSC-RX10M4", -800, 0, /* prelim */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, {"Sony DSC-RX0", -800, 0, /* temp */ { 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM3", 0, 0, /* temp */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace(string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x398, "EOS M100"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 = imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature = imgdata.other.exifAmbientTemperature = -1000.0f; for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread(head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head + 0x1c); memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); // bytes count width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // Data integrity check if(width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width*height) || i > (2* width*height)) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD /* no foveon support for dcraw build from libraw source */ parse_x3f(); #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); break; } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) strcpy(model, model + 8); if (!strncmp(model, "Digital Camera ", 15)) strcpy(model, model + 15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2)) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c, A6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; #ifdef LIBRAW_LIBRARY_BUILD float fratio = float(data_size) / (float(raw_height) * float(raw_width)); if(!(raw_width % 10) && !(data_size % 16384) && fratio >= 1.6f && fratio <= 1.6001f) { load_raw = &CLASS panasonic_16x10_load_raw; zero_is_bad = 0; } #endif if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } //@end COMMON //@out FILEIO #ifndef NO_LCMS void CLASS apply_profile(const char *input, const char *output) { char *prof; cmsHPROFILE hInProfile = 0, hOutProfile = 0; cmsHTRANSFORM hTransform; FILE *fp; unsigned size; if (strcmp(input, "embed")) hInProfile = cmsOpenProfileFromFile(input, "r"); else if (profile_length) { #ifndef LIBRAW_LIBRARY_BUILD prof = (char *)malloc(profile_length); merror(prof, "apply_profile()"); fseek(ifp, profile_offset, SEEK_SET); fread(prof, 1, profile_length, ifp); hInProfile = cmsOpenProfileFromMem(prof, profile_length); free(prof); #else hInProfile = cmsOpenProfileFromMem(imgdata.color.profile, profile_length); #endif } else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s has no embedded profile.\n"), ifname); #endif } if (!hInProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE; #endif return; } if (!output) hOutProfile = cmsCreate_sRGBProfile(); else if ((fp = fopen(output, "rb"))) { fread(&size, 4, 1, fp); fseek(fp, 0, SEEK_SET); oprof = (unsigned *)malloc(size = ntohl(size)); merror(oprof, "apply_profile()"); fread(oprof, 1, size, fp); fclose(fp); if (!(hOutProfile = cmsOpenProfileFromMem(oprof, size))) { free(oprof); oprof = 0; } } #ifdef DCRAW_VERBOSE else fprintf(stderr, _("Cannot open file %s!\n"), output); #endif if (!hOutProfile) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE; #endif goto quit; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Applying color profile...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 0, 2); #endif hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_16, hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0); cmsDoTransform(hTransform, image, image, width * height); raw_color = 1; /* Don't use rgb_cam with a profile */ cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); quit: cmsCloseProfile(hInProfile); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE, 1, 2); #endif } #endif //@end FILEIO //@out COMMON void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } //@end COMMON struct tiff_tag { ushort tag, type; int count; union { char c[4]; short s[2]; int i; } val; }; struct tiff_hdr { ushort t_order, magic; int ifd; ushort pad, ntag; struct tiff_tag tag[23]; int nextifd; ushort pad2, nexif; struct tiff_tag exif[4]; ushort pad3, ngps; struct tiff_tag gpst[10]; short bps[4]; int rat[10]; unsigned gps[26]; char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64]; }; //@out COMMON void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); } //@end COMMON int CLASS main(int argc, const char **argv) { int arg, status = 0, quality, i, c; int timestamp_only = 0, thumbnail_only = 0, identify_only = 0; int user_qual = -1, user_black = -1, user_sat = -1, user_flip = -1; int use_fuji_rotate = 1, write_to_stdout = 0, read_from_stdin = 0; const char *sp, *bpfile = 0, *dark_frame = 0, *write_ext; char opm, opt, *ofname, *cp; struct utimbuf ut; #ifndef NO_LCMS const char *cam_profile = 0, *out_profile = 0; #endif #ifndef LOCALTIME putenv((char *)"TZ=UTC"); #endif #ifdef LOCALEDIR setlocale(LC_CTYPE, ""); setlocale(LC_MESSAGES, ""); bindtextdomain("dcraw", LOCALEDIR); textdomain("dcraw"); #endif if (argc == 1) { printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION); printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n")); printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]); puts(_("-v Print verbose messages")); puts(_("-c Write image data to standard output")); puts(_("-e Extract embedded thumbnail image")); puts(_("-i Identify files without decoding them")); puts(_("-i -v Identify files and show metadata")); puts(_("-z Change file dates to camera timestamp")); puts(_("-w Use camera white balance, if possible")); puts(_("-a Average the whole image for white balance")); puts(_("-A <x y w h> Average a grey box for white balance")); puts(_("-r <r g b g> Set custom white balance")); puts(_("+M/-M Use/don't use an embedded color matrix")); puts(_("-C <r b> Correct chromatic aberration")); puts(_("-P <file> Fix the dead pixels listed in this file")); puts(_("-K <file> Subtract dark frame (16-bit raw PGM)")); puts(_("-k <num> Set the darkness level")); puts(_("-S <num> Set the saturation level")); puts(_("-n <num> Set threshold for wavelet denoising")); puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)")); puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)")); puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)")); #ifndef NO_LCMS puts(_("-o <file> Apply output ICC profile from file")); puts(_("-p <file> Apply camera ICC profile from file or \"embed\"")); #endif puts(_("-d Document mode (no color, no interpolation)")); puts(_("-D Document mode without scaling (totally raw)")); puts(_("-j Don't stretch or rotate raw pixels")); puts(_("-W Don't automatically brighten the image")); puts(_("-b <num> Adjust brightness (default = 1.0)")); puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)")); puts(_("-q [0-3] Set the interpolation quality")); puts(_("-h Half-size color image (twice as fast as \"-q 0\")")); puts(_("-f Interpolate RGGB as four colors")); puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G")); puts(_("-s [0..N-1] Select one raw image or \"all\" from each file")); puts(_("-6 Write 16-bit instead of 8-bit")); puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\"")); puts(_("-T Write TIFF instead of PPM")); puts(""); return 1; } argv[argc] = ""; for (arg = 1; (((opm = argv[arg][0]) - 2) | 2) == '+';) { opt = argv[arg++][1]; if ((cp = (char *)strchr(sp = "nbrkStqmHACg", opt))) for (i = 0; i < "114111111422"[cp - sp] - '0'; i++) if (!isdigit(argv[arg + i][0])) { fprintf(stderr, _("Non-numeric argument to \"-%c\"\n"), opt); return 1; } switch (opt) { case 'n': threshold = atof(argv[arg++]); break; case 'b': bright = atof(argv[arg++]); break; case 'r': FORC4 user_mul[c] = atof(argv[arg++]); break; case 'C': aber[0] = 1 / atof(argv[arg++]); aber[2] = 1 / atof(argv[arg++]); break; case 'g': gamm[0] = atof(argv[arg++]); gamm[1] = atof(argv[arg++]); if (gamm[0]) gamm[0] = 1 / gamm[0]; break; case 'k': user_black = atoi(argv[arg++]); break; case 'S': user_sat = atoi(argv[arg++]); break; case 't': user_flip = atoi(argv[arg++]); break; case 'q': user_qual = atoi(argv[arg++]); break; case 'm': med_passes = atoi(argv[arg++]); break; case 'H': highlight = atoi(argv[arg++]); break; case 's': shot_select = abs(atoi(argv[arg])); multi_out = !strcmp(argv[arg++], "all"); break; case 'o': if (isdigit(argv[arg][0]) && !argv[arg][1]) output_color = atoi(argv[arg++]); #ifndef NO_LCMS else out_profile = argv[arg++]; break; case 'p': cam_profile = argv[arg++]; #endif break; case 'P': bpfile = argv[arg++]; break; case 'K': dark_frame = argv[arg++]; break; case 'z': timestamp_only = 1; break; case 'e': thumbnail_only = 1; break; case 'i': identify_only = 1; break; case 'c': write_to_stdout = 1; break; case 'v': verbose = 1; break; case 'h': half_size = 1; break; case 'f': four_color_rgb = 1; break; case 'A': FORC4 greybox[c] = atoi(argv[arg++]); case 'a': use_auto_wb = 1; break; case 'w': use_camera_wb = 1; break; case 'M': use_camera_matrix = 3 * (opm == '+'); break; case 'I': read_from_stdin = 1; break; case 'E': document_mode++; case 'D': document_mode++; case 'd': document_mode++; case 'j': use_fuji_rotate = 0; break; case 'W': no_auto_bright = 1; break; case 'T': output_tiff = 1; break; case '4': gamm[0] = gamm[1] = no_auto_bright = 1; case '6': output_bps = 16; break; default: fprintf(stderr, _("Unknown option \"-%c\".\n"), opt); return 1; } } if (arg == argc) { fprintf(stderr, _("No files to process.\n")); return 1; } if (write_to_stdout) { if (isatty(1)) { fprintf(stderr, _("Will not write an image to the terminal!\n")); return 1; } #if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__) if (setmode(1, O_BINARY) < 0) { perror("setmode()"); return 1; } #endif } for (; arg < argc; arg++) { status = 1; raw_image = 0; image = 0; oprof = 0; meta_data = ofname = 0; ofp = stdout; if (setjmp(failure)) { if (fileno(ifp) > 2) fclose(ifp); if (fileno(ofp) > 2) fclose(ofp); status = 1; goto cleanup; } ifname = argv[arg]; if (!(ifp = fopen(ifname, "rb"))) { perror(ifname); continue; } status = (identify(), !is_raw); if (user_flip >= 0) flip = user_flip; switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; } if (timestamp_only) { if ((status = !timestamp)) fprintf(stderr, _("%s has no timestamp.\n"), ifname); else if (identify_only) printf("%10ld%10d %s\n", (long)timestamp, shot_order, ifname); else { if (verbose) fprintf(stderr, _("%s time set to %d.\n"), ifname, (int)timestamp); ut.actime = ut.modtime = timestamp; utime(ifname, &ut); } goto next; } write_fun = &CLASS write_ppm_tiff; if (thumbnail_only) { if ((status = !thumb_offset)) { fprintf(stderr, _("%s has no thumbnail.\n"), ifname); goto next; } else if (thumb_load_raw) { load_raw = thumb_load_raw; data_offset = thumb_offset; height = thumb_height; width = thumb_width; filters = 0; colors = 3; } else { fseek(ifp, thumb_offset, SEEK_SET); write_fun = write_thumb; goto thumbnail; } } if (load_raw == &CLASS kodak_ycbcr_load_raw) { height += height & 1; width += width & 1; } if (identify_only && verbose && make[0]) { printf(_("\nFilename: %s\n"), ifname); printf(_("Timestamp: %s"), ctime(&timestamp)); printf(_("Camera: %s %s\n"), make, model); if (artist[0]) printf(_("Owner: %s\n"), artist); if (dng_version) { printf(_("DNG Version: ")); for (i = 24; i >= 0; i -= 8) printf("%d%c", dng_version >> i & 255, i ? '.' : '\n'); } printf(_("ISO speed: %d\n"), (int)iso_speed); printf(_("Shutter: ")); if (shutter > 0 && shutter < 1) shutter = (printf("1/"), 1 / shutter); printf(_("%0.1f sec\n"), shutter); printf(_("Aperture: f/%0.1f\n"), aperture); printf(_("Focal length: %0.1f mm\n"), focal_len); printf(_("Embedded ICC profile: %s\n"), profile_length ? _("yes") : _("no")); printf(_("Number of raw images: %d\n"), is_raw); if (pixel_aspect != 1) printf(_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect); if (thumb_offset) printf(_("Thumb size: %4d x %d\n"), thumb_width, thumb_height); printf(_("Full size: %4d x %d\n"), raw_width, raw_height); } else if (!is_raw) fprintf(stderr, _("Cannot decode file %s\n"), ifname); if (!is_raw) goto next; shrink = filters && (half_size || (!identify_only && (threshold || aber[0] != 1 || aber[2] != 1))); iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (identify_only) { if (verbose) { if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (use_fuji_rotate) { if (fuji_width) { fuji_width = (fuji_width - 1 + shrink) >> shrink; iwidth = fuji_width / sqrt(0.5); iheight = (iheight - fuji_width) / sqrt(0.5); } else { if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5; if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5; } } if (flip & 4) SWAP(iheight, iwidth); printf(_("Image size: %4d x %d\n"), width, height); printf(_("Output size: %4d x %d\n"), iwidth, iheight); printf(_("Raw colors: %d"), colors); if (filters) { int fhigh = 2, fwide = 2; if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4; if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8; if (filters == 1) fhigh = fwide = 16; if (filters == 9) fhigh = fwide = 6; printf(_("\nFilter pattern: ")); for (i = 0; i < fhigh; i++) for (c = i && putchar('/') && 0; c < fwide; c++) putchar(cdesc[fcol(i, c)]); } printf(_("\nDaylight multipliers:")); FORCC printf(" %f", pre_mul[c]); if (cam_mul[0] > 0) { printf(_("\nCamera multipliers:")); FORC4 printf(" %f", cam_mul[c]); } putchar('\n'); } else printf(_("%s is a %s %s image.\n"), ifname, make, model); next: fclose(ifp); continue; } if (meta_length) { meta_data = (char *)malloc(meta_length); merror(meta_data, "main()"); } if (filters || colors == 1) { raw_image = (ushort *)calloc((raw_height + 7), raw_width * 2); merror(raw_image, "main()"); } else { image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image); merror(image, "main()"); } if (verbose) fprintf(stderr, _("Loading %s %s image from %s ...\n"), make, model, ifname); if (shot_select >= is_raw) fprintf(stderr, _("%s: \"-s %d\" requests a nonexistent image!\n"), ifname, shot_select); fseeko(ifp, data_offset, SEEK_SET); if (raw_image && read_from_stdin) fread(raw_image, 2, raw_height * raw_width, stdin); else (*load_raw)(); if (document_mode == 3) { top_margin = left_margin = fuji_width = 0; height = raw_height; width = raw_width; } iheight = (height + shrink) >> shrink; iwidth = (width + shrink) >> shrink; if (raw_image) { image = (ushort(*)[4])calloc(iheight, iwidth * sizeof *image); merror(image, "main()"); crop_masked_pixels(); free(raw_image); } if (zero_is_bad) remove_zeroes(); bad_pixels(bpfile); if (dark_frame) subtract(dark_frame); quality = 2 + !fuji_width; if (user_qual >= 0) quality = user_qual; i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; i = cblack[6]; FORC(cblack[4] * cblack[5]) if (i > cblack[6 + c]) i = cblack[6 + c]; FORC(cblack[4] * cblack[5]) cblack[6 + c] -= i; black += i; if (user_black >= 0) black = user_black; FORC4 cblack[c] += black; if (user_sat > 0) maximum = user_sat; #ifdef COLORCHECK colorcheck(); #endif if (is_foveon) { if (document_mode || load_raw == &CLASS foveon_dp_load_raw) { for (i = 0; i < height * width * 4; i++) if ((short)image[0][i] < 0) image[0][i] = 0; } else foveon_interpolate(); } else if (document_mode < 2) scale_colors(); pre_interpolate(); if (filters && !document_mode) { if (quality == 0) lin_interpolate(); else if (quality == 1 || colors > 3) vng_interpolate(); else if (quality == 2 && filters > 1000) ppg_interpolate(); else if (filters == 9) xtrans_interpolate(quality * 2 - 3); else ahd_interpolate(); } if (mix_green) for (colors = 3, i = 0; i < height * width; i++) image[i][1] = (image[i][1] + image[i][3]) >> 1; if (!is_foveon && colors == 3) median_filter(); if (!is_foveon && highlight == 2) blend_highlights(); if (!is_foveon && highlight > 2) recover_highlights(); if (use_fuji_rotate) fuji_rotate(); #ifndef NO_LCMS if (cam_profile) apply_profile(cam_profile, out_profile); #endif convert_to_rgb(); if (use_fuji_rotate) stretch(); thumbnail: if (write_fun == &CLASS jpeg_thumb) write_ext = ".jpg"; else if (output_tiff && write_fun == &CLASS write_ppm_tiff) write_ext = ".tiff"; else write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors * 5 - 5; ofname = (char *)malloc(strlen(ifname) + 64); merror(ofname, "main()"); if (write_to_stdout) strcpy(ofname, _("standard output")); else { strcpy(ofname, ifname); if ((cp = strrchr(ofname, '.'))) *cp = 0; if (multi_out) sprintf(ofname + strlen(ofname), "_%0*d", snprintf(0, 0, "%d", is_raw - 1), shot_select); if (thumbnail_only) strcat(ofname, ".thumb"); strcat(ofname, write_ext); ofp = fopen(ofname, "wb"); if (!ofp) { status = 1; perror(ofname); goto cleanup; } } if (verbose) fprintf(stderr, _("Writing data to %s ...\n"), ofname); (*write_fun)(); fclose(ifp); if (ofp != stdout) fclose(ofp); cleanup: if (meta_data) free(meta_data); if (ofname) free(ofname); if (oprof) free(oprof); if (image) free(image); if (multi_out) { if (++shot_select < is_raw) arg--; else shot_select = 0; } } return status; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2946_0
crossvul-cpp_data_good_486_0
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. ASN.1 utility functions Copyright 2012-2017 Henrik Andersson <hean01@cendio.se> for Cendio AB 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 3 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 "rdesktop.h" /* Parse an ASN.1 BER header */ RD_BOOL ber_parse_header(STREAM s, int tagval, uint32 *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); } void ber_out_sequence(STREAM out, STREAM content) { size_t length; length = (content ? s_length(content) : 0); ber_out_header(out, BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, length); if (content) out_stream(out, content); } /* Output an ASN.1 BER header */ void ber_out_header(STREAM s, int tagval, int length) { if (tagval > 0xff) { out_uint16_be(s, tagval); } else { out_uint8(s, tagval); } if (length >= 0x80) { out_uint8(s, 0x82); out_uint16_be(s, length); } else out_uint8(s, length); } /* Output an ASN.1 BER integer */ void ber_out_integer(STREAM s, int value) { ber_out_header(s, BER_TAG_INTEGER, 2); out_uint16_be(s, value); } RD_BOOL ber_in_header(STREAM s, int *tagval, int *decoded_len) { in_uint8(s, *tagval); in_uint8(s, *decoded_len); if (*decoded_len < 0x80) return True; else if (*decoded_len == 0x81) { in_uint8(s, *decoded_len); return True; } else if (*decoded_len == 0x82) { in_uint16_be(s, *decoded_len); return True; } return False; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_486_0
crossvul-cpp_data_bad_3190_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3190_0
crossvul-cpp_data_bad_5082_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | 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: Kirti Velankar <kirtig@yahoo-inc.com> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <unicode/ustring.h> #include <unicode/udata.h> #include <unicode/putil.h> #include <unicode/ures.h> #include "php_intl.h" #include "locale.h" #include "locale_class.h" #include "locale_methods.h" #include "intl_convert.h" #include "intl_data.h" #include <zend_API.h> #include <zend.h> #include <php.h> #include "main/php_ini.h" #include "ext/standard/php_smart_str.h" ZEND_EXTERN_MODULE_GLOBALS( intl ) /* Sizes required for the strings "variant15" , "extlang11", "private12" etc. */ #define SEPARATOR "_" #define SEPARATOR1 "-" #define DELIMITER "-_" #define EXTLANG_PREFIX "a" #define PRIVATE_PREFIX "x" #define DISP_NAME "name" #define MAX_NO_VARIANT 15 #define MAX_NO_EXTLANG 3 #define MAX_NO_PRIVATE 15 #define MAX_NO_LOOKUP_LANG_TAG 100 #define LOC_NOT_FOUND 1 /* Sizes required for the strings "variant15" , "extlang3", "private12" etc. */ #define VARIANT_KEYNAME_LEN 11 #define EXTLANG_KEYNAME_LEN 10 #define PRIVATE_KEYNAME_LEN 11 /* Based on IANA registry at the time of writing this code * */ static const char * const LOC_GRANDFATHERED[] = { "art-lojban", "i-klingon", "i-lux", "i-navajo", "no-bok", "no-nyn", "cel-gaulish", "en-GB-oed", "i-ami", "i-bnn", "i-default", "i-enochian", "i-mingo", "i-pwn", "i-tao", "i-tay", "i-tsu", "sgn-BE-fr", "sgn-BE-nl", "sgn-CH-de", "zh-cmn", "zh-cmn-Hans", "zh-cmn-Hant", "zh-gan" , "zh-guoyu", "zh-hakka", "zh-min", "zh-min-nan", "zh-wuu", "zh-xiang", "zh-yue", NULL }; /* Based on IANA registry at the time of writing this code * This array lists the preferred values for the grandfathered tags if applicable * This is in sync with the array LOC_GRANDFATHERED * e.g. the offsets of the grandfathered tags match the offset of the preferred value */ static const int LOC_PREFERRED_GRANDFATHERED_LEN = 6; static const char * const LOC_PREFERRED_GRANDFATHERED[] = { "jbo", "tlh", "lb", "nv", "nb", "nn", NULL }; /*returns TRUE if a is an ID separator FALSE otherwise*/ #define isIDSeparator(a) (a == '_' || a == '-') #define isKeywordSeparator(a) (a == '@' ) #define isEndOfTag(a) (a == '\0' ) #define isPrefixLetter(a) ((a=='x')||(a=='X')||(a=='i')||(a=='I')) /*returns TRUE if one of the special prefixes is here (s=string) 'x-' or 'i-' */ #define isIDPrefix(s) (isPrefixLetter(s[0])&&isIDSeparator(s[1])) #define isKeywordPrefix(s) ( isKeywordSeparator(s[0]) ) /* Dot terminates it because of POSIX form where dot precedes the codepage * except for variant */ #define isTerminator(a) ((a==0)||(a=='.')||(a=='@')) /* {{{ return the offset of 'key' in the array 'list'. * returns -1 if not present */ static int16_t findOffset(const char* const* list, const char* key) { const char* const* anchor = list; while (*list != NULL) { if (strcmp(key, *list) == 0) { return (int16_t)(list - anchor); } list++; } return -1; } /*}}}*/ static char* getPreferredTag(const char* gf_tag) { char* result = NULL; int grOffset = 0; grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag); if(grOffset < 0) { return NULL; } if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){ /* return preferred tag */ result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] ); } else { /* Return correct grandfathered language tag */ result = estrdup( LOC_GRANDFATHERED[grOffset] ); } return result; } /* {{{ * returns the position of next token for lookup * or -1 if no token * strtokr equivalent search for token in reverse direction */ static int getStrrtokenPos(char* str, int savedPos) { int result =-1; int i; for(i=savedPos-1; i>=0; i--) { if(isIDSeparator(*(str+i)) ){ /* delimiter found; check for singleton */ if(i>=2 && isIDSeparator(*(str+i-2)) ){ /* a singleton; so send the position of token before the singleton */ result = i-2; } else { result = i; } break; } } if(result < 1){ /* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */ result =-1; } return result; } /* }}} */ /* {{{ * returns the position of a singleton if present * returns -1 if no singleton * strtok equivalent search for singleton */ static int getSingletonPos(const char* str) { int result =-1; int i=0; int len = 0; if( str && ((len=strlen(str))>0) ){ for( i=0; i<len ; i++){ if( isIDSeparator(*(str+i)) ){ if( i==1){ /* string is of the form x-avy or a-prv1 */ result =0; break; } else { /* delimiter found; check for singleton */ if( isIDSeparator(*(str+i+2)) ){ /* a singleton; so send the position of separator before singleton */ result = i+1; break; } } } }/* end of for */ } return result; } /* }}} */ /* {{{ proto static string Locale::getDefault( ) Get default locale */ /* }}} */ /* {{{ proto static string locale_get_default( ) Get default locale */ PHP_NAMED_FUNCTION(zif_locale_get_default) { RETURN_STRING( intl_locale_get_default( TSRMLS_C ), TRUE ); } /* }}} */ /* {{{ proto static string Locale::setDefault( string $locale ) Set default locale */ /* }}} */ /* {{{ proto static string locale_set_default( string $locale ) Set default locale */ PHP_NAMED_FUNCTION(zif_locale_set_default) { char* locale_name = NULL; int len=0; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &locale_name ,&len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_set_default: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(len == 0) { locale_name = (char *)uloc_getDefault() ; len = strlen(locale_name); } zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); RETURN_TRUE; } /* }}} */ /* {{{ * Gets the value from ICU * common code shared by get_primary_language,get_script or get_region or get_variant * result = 0 if error, 1 if successful , -1 if no value */ static char* get_icu_value_internal( const char* loc_name , char* tag_name, int* result , int fromParseLocale) { char* tag_value = NULL; int32_t tag_value_len = 512; int singletonPos = 0; char* mod_loc_name = NULL; int grOffset = 0; int32_t buflen = 512; UErrorCode status = U_ZERO_ERROR; if( strcmp(tag_name, LOC_CANONICALIZE_TAG) != 0 ){ /* Handle grandfathered languages */ grOffset = findOffset( LOC_GRANDFATHERED , loc_name ); if( grOffset >= 0 ){ if( strcmp(tag_name , LOC_LANG_TAG)==0 ){ return estrdup(loc_name); } else { /* Since Grandfathered , no value , do nothing , retutn NULL */ return NULL; } } if( fromParseLocale==1 ){ /* Handle singletons */ if( strcmp(tag_name , LOC_LANG_TAG)==0 ){ if( strlen(loc_name)>1 && (isIDPrefix(loc_name) == 1) ){ return estrdup(loc_name); } } singletonPos = getSingletonPos( loc_name ); if( singletonPos == 0){ /* singleton at start of script, region , variant etc. * or invalid singleton at start of language */ return NULL; } else if( singletonPos > 0 ){ /* singleton at some position except at start * strip off the singleton and rest of the loc_name */ mod_loc_name = estrndup ( loc_name , singletonPos-1); } } /* end of if fromParse */ } /* end of if != LOC_CANONICAL_TAG */ if( mod_loc_name == NULL){ mod_loc_name = estrdup(loc_name ); } /* Proceed to ICU */ do{ tag_value = erealloc( tag_value , buflen ); tag_value_len = buflen; if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){ buflen = uloc_getScript ( mod_loc_name ,tag_value , tag_value_len , &status); } if( strcmp(tag_name , LOC_LANG_TAG )==0 ){ buflen = uloc_getLanguage ( mod_loc_name ,tag_value , tag_value_len , &status); } if( strcmp(tag_name , LOC_REGION_TAG)==0 ){ buflen = uloc_getCountry ( mod_loc_name ,tag_value , tag_value_len , &status); } if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){ buflen = uloc_getVariant ( mod_loc_name ,tag_value , tag_value_len , &status); } if( strcmp(tag_name , LOC_CANONICALIZE_TAG)==0 ){ buflen = uloc_canonicalize ( mod_loc_name ,tag_value , tag_value_len , &status); } if( U_FAILURE( status ) ) { if( status == U_BUFFER_OVERFLOW_ERROR ) { status = U_ZERO_ERROR; continue; } /* Error in retriving data */ *result = 0; if( tag_value ){ efree( tag_value ); } if( mod_loc_name ){ efree( mod_loc_name); } return NULL; } } while( buflen > tag_value_len ); if( buflen ==0 ){ /* No value found */ *result = -1; if( tag_value ){ efree( tag_value ); } if( mod_loc_name ){ efree( mod_loc_name); } return NULL; } else { *result = 1; } if( mod_loc_name ){ efree( mod_loc_name); } return tag_value; } /* }}} */ /* {{{ * Gets the value from ICU , called when PHP userspace function is called * common code shared by get_primary_language,get_script or get_region or get_variant */ static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; char* tag_value = NULL; char* empty_result = ""; int result = 0; char* msg = NULL; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name ,&loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Call ICU get */ tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0); /* No value found */ if( result == -1 ) { if( tag_value){ efree( tag_value); } RETURN_STRING( empty_result , TRUE); } /* value found */ if( tag_value){ RETURN_STRING( tag_value , FALSE); } /* Error encountered while fetching the value */ if( result ==0) { spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_NULL(); } } /* }}} */ /* {{{ proto static string Locale::getScript($locale) * gets the script for the $locale }}} */ /* {{{ proto static string locale_get_script($locale) * gets the script for the $locale */ PHP_FUNCTION( locale_get_script ) { get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ proto static string Locale::getRegion($locale) * gets the region for the $locale }}} */ /* {{{ proto static string locale_get_region($locale) * gets the region for the $locale */ PHP_FUNCTION( locale_get_region ) { get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ proto static string Locale::getPrimaryLanguage($locale) * gets the primary language for the $locale }}} */ /* {{{ proto static string locale_get_primary_language($locale) * gets the primary language for the $locale */ PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ * common code shared by display_xyz functions to get the value from ICU }}} */ static void get_icu_disp_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; const char* disp_loc_name = NULL; int disp_loc_name_len = 0; int free_loc_name = 0; UChar* disp_name = NULL; int32_t disp_name_len = 0; char* mod_loc_name = NULL; int32_t buflen = 512; UErrorCode status = U_ZERO_ERROR; char* utf8value = NULL; int utf8value_len = 0; char* msg = NULL; int grOffset = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &loc_name, &loc_name_len , &disp_loc_name ,&disp_loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_display_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len > ULOC_FULLNAME_CAPACITY) { /* See bug 67397: overlong locale names cause trouble in uloc_getDisplayName */ spprintf(&msg , 0, "locale_get_display_%s : name too long", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } if( strcmp(tag_name, DISP_NAME) != 0 ){ /* Handle grandfathered languages */ grOffset = findOffset( LOC_GRANDFATHERED , loc_name ); if( grOffset >= 0 ){ if( strcmp(tag_name , LOC_LANG_TAG)==0 ){ mod_loc_name = getPreferredTag( loc_name ); } else { /* Since Grandfathered, no value, do nothing, retutn NULL */ RETURN_FALSE; } } } /* end of if != LOC_CANONICAL_TAG */ if( mod_loc_name==NULL ){ mod_loc_name = estrdup( loc_name ); } /* Check if disp_loc_name passed , if not use default locale */ if( !disp_loc_name){ disp_loc_name = estrdup(intl_locale_get_default(TSRMLS_C)); free_loc_name = 1; } /* Get the disp_value for the given locale */ do{ disp_name = erealloc( disp_name , buflen * sizeof(UChar) ); disp_name_len = buflen; if( strcmp(tag_name , LOC_LANG_TAG)==0 ){ buflen = uloc_getDisplayLanguage ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status); } else if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){ buflen = uloc_getDisplayScript ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status); } else if( strcmp(tag_name , LOC_REGION_TAG)==0 ){ buflen = uloc_getDisplayCountry ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status); } else if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){ buflen = uloc_getDisplayVariant ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status); } else if( strcmp(tag_name , DISP_NAME)==0 ){ buflen = uloc_getDisplayName ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status); } /* U_STRING_NOT_TERMINATED_WARNING is admissible here; don't look for it */ if( U_FAILURE( status ) ) { if( status == U_BUFFER_OVERFLOW_ERROR ) { status = U_ZERO_ERROR; continue; } spprintf(&msg, 0, "locale_get_display_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); if( disp_name){ efree( disp_name ); } if( mod_loc_name){ efree( mod_loc_name ); } if (free_loc_name) { efree((void *)disp_loc_name); disp_loc_name = NULL; } RETURN_FALSE; } } while( buflen > disp_name_len ); if( mod_loc_name){ efree( mod_loc_name ); } if (free_loc_name) { efree((void *)disp_loc_name); disp_loc_name = NULL; } /* Convert display locale name from UTF-16 to UTF-8. */ intl_convert_utf16_to_utf8( &utf8value, &utf8value_len, disp_name, buflen, &status ); efree( disp_name ); if( U_FAILURE( status ) ) { spprintf(&msg, 0, "locale_get_display_%s :error converting display name for %s to UTF-8", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } RETVAL_STRINGL( utf8value, utf8value_len , FALSE); } /* }}} */ /* {{{ proto static string Locale::getDisplayName($locale[, $in_locale = null]) * gets the name for the $locale in $in_locale or default_locale }}} */ /* {{{ proto static string get_display_name($locale[, $in_locale = null]) * gets the name for the $locale in $in_locale or default_locale */ PHP_FUNCTION(locale_get_display_name) { get_icu_disp_value_src_php( DISP_NAME , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ proto static string Locale::getDisplayLanguage($locale[, $in_locale = null]) * gets the language for the $locale in $in_locale or default_locale }}} */ /* {{{ proto static string get_display_language($locale[, $in_locale = null]) * gets the language for the $locale in $in_locale or default_locale */ PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ proto static string Locale::getDisplayScript($locale, $in_locale = null) * gets the script for the $locale in $in_locale or default_locale }}} */ /* {{{ proto static string get_display_script($locale, $in_locale = null) * gets the script for the $locale in $in_locale or default_locale */ PHP_FUNCTION(locale_get_display_script) { get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ proto static string Locale::getDisplayRegion($locale, $in_locale = null) * gets the region for the $locale in $in_locale or default_locale }}} */ /* {{{ proto static string get_display_region($locale, $in_locale = null) * gets the region for the $locale in $in_locale or default_locale */ PHP_FUNCTION(locale_get_display_region) { get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ * proto static string Locale::getDisplayVariant($locale, $in_locale = null) * gets the variant for the $locale in $in_locale or default_locale }}} */ /* {{{ * proto static string get_display_variant($locale, $in_locale = null) * gets the variant for the $locale in $in_locale or default_locale */ PHP_FUNCTION(locale_get_display_variant) { get_icu_disp_value_src_php( LOC_VARIANT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ proto static array getKeywords(string $locale) { * return an associative array containing keyword-value * pairs for this locale. The keys are keys to the array (doh!) * }}}*/ /* {{{ proto static array locale_get_keywords(string $locale) { * return an associative array containing keyword-value * pairs for this locale. The keys are keys to the array (doh!) */ PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); } /* }}} */ /* {{{ proto static string Locale::canonicalize($locale) * @return string the canonicalized locale * }}} */ /* {{{ proto static string locale_canonicalize(Locale $loc, string $locale) * @param string $locale The locale string to canonicalize */ PHP_FUNCTION(locale_canonicalize) { get_icu_value_src_php( LOC_CANONICALIZE_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } /* }}} */ /* {{{ append_key_value * Internal function which is called from locale_compose * gets the value for the key_name and appends to the loc_name * returns 1 if successful , -1 if not found , * 0 if array element is not a string , -2 if buffer-overflow */ static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name) { zval** ele_value = NULL; if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if(Z_TYPE_PP(ele_value)!= IS_STRING ){ /* element value is not a string */ return FAILURE; } if(strcmp(key_name, LOC_LANG_TAG) != 0 && strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) { /* not lang or grandfathered tag */ smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); } smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } return LOC_NOT_FOUND; } /* }}} */ /* {{{ append_prefix , appends the prefix needed * e.g. private adds 'x' */ static void add_prefix(smart_str* loc_name, char* key_name) { if( strncmp(key_name , LOC_PRIVATE_TAG , 7) == 0 ){ smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, PRIVATE_PREFIX , sizeof(PRIVATE_PREFIX)-1); } } /* }}} */ /* {{{ append_multiple_key_values * Internal function which is called from locale_compose * gets the multiple values for the key_name and appends to the loc_name * used for 'variant','extlang','private' * returns 1 if successful , -1 if not found , * 0 if array element is not a string , -2 if buffer-overflow */ static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC) { zval** ele_value = NULL; int i = 0; int isFirstSubtag = 0; int max_value = 0; /* Variant/ Extlang/Private etc. */ if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if( Z_TYPE_PP(ele_value) == IS_STRING ){ add_prefix( loc_name , key_name); smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) { HashPosition pos; HashTable *arr = HASH_OF(*ele_value); zval **data = NULL; zend_hash_internal_pointer_reset_ex(arr, &pos); while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) { if(Z_TYPE_PP(data) != IS_STRING) { return FAILURE; } if (isFirstSubtag++ == 0){ add_prefix(loc_name , key_name); } smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data)); zend_hash_move_forward_ex(arr, &pos); } return SUCCESS; } else { return FAILURE; } } else { char cur_key_name[31]; /* Decide the max_value: the max. no. of elements allowed */ if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){ max_value = MAX_NO_VARIANT; } if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){ max_value = MAX_NO_EXTLANG; } if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){ max_value = MAX_NO_PRIVATE; } /* Multiple variant values as variant0, variant1 ,variant2 */ isFirstSubtag = 0; for( i=0 ; i< max_value; i++ ){ snprintf( cur_key_name , 30, "%s%d", key_name , i); if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){ if( Z_TYPE_PP(ele_value)!= IS_STRING ){ /* variant is not a string */ return FAILURE; } /* Add the contents */ if (isFirstSubtag++ == 0){ add_prefix(loc_name , cur_key_name); } smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); } } /* end of for */ } /* end of else */ return SUCCESS; } /* }}} */ /*{{{ * If applicable sets error message and aborts locale_compose gracefully * returns 0 if locale_compose needs to be aborted * otherwise returns 1 */ static int handleAppendResult( int result, smart_str* loc_name TSRMLS_DC) { intl_error_reset( NULL TSRMLS_CC ); if( result == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: parameter array element is not a string", 0 TSRMLS_CC ); smart_str_free(loc_name); return 0; } return 1; } /* }}} */ #define RETURN_SMART_STR(s) smart_str_0((s)); RETURN_STRINGL((s)->c, (s)->len, 0) /* {{{ proto static string Locale::composeLocale($array) * Creates a locale by combining the parts of locale-ID passed * }}} */ /* {{{ proto static string compose_locale($array) * Creates a locale by combining the parts of locale-ID passed * }}} */ PHP_FUNCTION(locale_compose) { smart_str loc_name_s = {0}; smart_str *loc_name = &loc_name_s; zval* arr = NULL; HashTable* hash_arr = NULL; int result = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } hash_arr = HASH_OF( arr ); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) RETURN_FALSE; /* Check for grandfathered first */ result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG); if( result == SUCCESS){ RETURN_SMART_STR(loc_name); } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Not grandfathered */ result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG); if( result == LOC_NOT_FOUND ){ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC ); smart_str_free(loc_name); RETURN_FALSE; } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Extlang */ result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Script */ result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Region */ result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Variant */ result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Private */ result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } RETURN_SMART_STR(loc_name); } /* }}} */ /*{{{ * Parses the locale and returns private subtags if existing * else returns NULL * e.g. for locale='en_US-x-prv1-prv2-prv3' * returns a pointer to the string 'prv1-prv2-prv3' */ static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } /* }}} */ /* {{{ code used by locale_parse */ static int add_array_entry(const char* loc_name, zval* hash_arr, char* key_name TSRMLS_DC) { char* key_value = NULL; char* cur_key_name = NULL; char* token = NULL; char* last_ptr = NULL; int result = 0; int cur_result = 0; int cnt = 0; if( strcmp(key_name , LOC_PRIVATE_TAG)==0 ){ key_value = get_private_subtags( loc_name ); result = 1; } else { key_value = get_icu_value_internal( loc_name , key_name , &result,1 ); } if( (strcmp(key_name , LOC_PRIVATE_TAG)==0) || ( strcmp(key_name , LOC_VARIANT_TAG)==0) ){ if( result > 0 && key_value){ /* Tokenize on the "_" or "-" */ token = php_strtok_r( key_value , DELIMITER ,&last_ptr); if( cur_key_name ){ efree( cur_key_name); } cur_key_name = (char*)ecalloc( 25, 25); sprintf( cur_key_name , "%s%d", key_name , cnt++); add_assoc_string( hash_arr, cur_key_name , token ,TRUE ); /* tokenize on the "_" or "-" and stop at singleton if any */ while( (token = php_strtok_r(NULL , DELIMITER , &last_ptr)) && (strlen(token)>1) ){ sprintf( cur_key_name , "%s%d", key_name , cnt++); add_assoc_string( hash_arr, cur_key_name , token , TRUE ); } /* if( strcmp(key_name, LOC_PRIVATE_TAG) == 0 ){ } */ } } else { if( result == 1 ){ add_assoc_string( hash_arr, key_name , key_value , TRUE ); cur_result = 1; } } if( cur_key_name ){ efree( cur_key_name); } /*if( key_name != LOC_PRIVATE_TAG && key_value){*/ if( key_value){ efree(key_value); } return cur_result; } /* }}} */ /* {{{ proto static array Locale::parseLocale($locale) * parses a locale-id into an array the different parts of it }}} */ /* {{{ proto static array parse_locale($locale) * parses a locale-id into an array the different parts of it */ PHP_FUNCTION(locale_parse) { const char* loc_name = NULL; int loc_name_len = 0; int grOffset = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_parse: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } array_init( return_value ); grOffset = findOffset( LOC_GRANDFATHERED , loc_name ); if( grOffset >= 0 ){ add_assoc_string( return_value , LOC_GRANDFATHERED_LANG_TAG , estrdup(loc_name) ,FALSE ); } else{ /* Not grandfathered */ add_array_entry( loc_name , return_value , LOC_LANG_TAG TSRMLS_CC); add_array_entry( loc_name , return_value , LOC_SCRIPT_TAG TSRMLS_CC); add_array_entry( loc_name , return_value , LOC_REGION_TAG TSRMLS_CC); add_array_entry( loc_name , return_value , LOC_VARIANT_TAG TSRMLS_CC); add_array_entry( loc_name , return_value , LOC_PRIVATE_TAG TSRMLS_CC); } } /* }}} */ /* {{{ proto static array Locale::getAllVariants($locale) * gets an array containing the list of variants, or null }}} */ /* {{{ proto static array locale_get_all_variants($locale) * gets an array containing the list of variants, or null */ PHP_FUNCTION(locale_get_all_variants) { const char* loc_name = NULL; int loc_name_len = 0; int result = 0; char* token = NULL; char* variant = NULL; char* saved_ptr = NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_parse: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } array_init( return_value ); /* If the locale is grandfathered, stop, no variants */ if( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){ /* ("Grandfathered Tag. No variants."); */ } else { /* Call ICU variant */ variant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0); if( result > 0 && variant){ /* Tokenize on the "_" or "-" */ token = php_strtok_r( variant , DELIMITER , &saved_ptr); add_next_index_stringl( return_value, token , strlen(token) ,TRUE ); /* tokenize on the "_" or "-" and stop at singleton if any */ while( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){ add_next_index_stringl( return_value, token , strlen(token) ,TRUE ); } } if( variant ){ efree( variant ); } } } /* }}} */ /*{{{ * Converts to lower case and also replaces all hyphens with the underscore */ static int strToMatch(const char* str ,char *retstr) { char* anchor = NULL; const char* anchor1 = NULL; int result = 0; if( (!str) || str[0] == '\0'){ return result; } else { anchor = retstr; anchor1 = str; while( (*str)!='\0' ){ if( *str == '-' ){ *retstr = '_'; } else { *retstr = tolower(*str); } str++; retstr++; } *retstr = '\0'; retstr= anchor; str= anchor1; result = 1; } return(result); } /* }}} */ /* {{{ proto static boolean Locale::filterMatches(string $langtag, string $locale[, bool $canonicalize]) * Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm */ /* }}} */ /* {{{ proto boolean locale_filter_matches(string $langtag, string $locale[, bool $canonicalize]) * Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm */ PHP_FUNCTION(locale_filter_matches) { char* lang_tag = NULL; int lang_tag_len = 0; const char* loc_range = NULL; int loc_range_len = 0; int result = 0; char* token = 0; char* chrcheck = NULL; char* can_lang_tag = NULL; char* can_loc_range = NULL; char* cur_lang_tag = NULL; char* cur_loc_range = NULL; zend_bool boolCanonical = 0; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &lang_tag, &lang_tag_len , &loc_range , &loc_range_len , &boolCanonical) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_filter_matches: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } if( strcmp(loc_range,"*")==0){ RETURN_TRUE; } if( boolCanonical ){ /* canonicalize loc_range */ can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0); if( result ==0) { intl_error_set( NULL, status, "locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC ); RETURN_FALSE; } /* canonicalize lang_tag */ can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0); if( result ==0) { intl_error_set( NULL, status, "locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC ); RETURN_FALSE; } /* Convert to lower case for case-insensitive comparison */ cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1); /* Convert to lower case for case-insensitive comparison */ result = strToMatch( can_lang_tag , cur_lang_tag); if( result == 0) { efree( cur_lang_tag ); efree( can_lang_tag ); RETURN_FALSE; } cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1); result = strToMatch( can_loc_range , cur_loc_range ); if( result == 0) { efree( cur_lang_tag ); efree( can_lang_tag ); efree( cur_loc_range ); efree( can_loc_range ); RETURN_FALSE; } /* check if prefix */ token = strstr( cur_lang_tag , cur_loc_range ); if( token && (token==cur_lang_tag) ){ /* check if the char. after match is SEPARATOR */ chrcheck = token + (strlen(cur_loc_range)); if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } if( can_lang_tag){ efree( can_lang_tag ); } if( can_loc_range){ efree( can_loc_range ); } RETURN_TRUE; } } /* No prefix as loc_range */ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } if( can_lang_tag){ efree( can_lang_tag ); } if( can_loc_range){ efree( can_loc_range ); } RETURN_FALSE; } /* end of if isCanonical */ else{ /* Convert to lower case for case-insensitive comparison */ cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1); result = strToMatch( lang_tag , cur_lang_tag); if( result == 0) { efree( cur_lang_tag ); RETURN_FALSE; } cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1); result = strToMatch( loc_range , cur_loc_range ); if( result == 0) { efree( cur_lang_tag ); efree( cur_loc_range ); RETURN_FALSE; } /* check if prefix */ token = strstr( cur_lang_tag , cur_loc_range ); if( token && (token==cur_lang_tag) ){ /* check if the char. after match is SEPARATOR */ chrcheck = token + (strlen(cur_loc_range)); if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } RETURN_TRUE; } } /* No prefix as loc_range */ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } RETURN_FALSE; } } /* }}} */ static void array_cleanup( char* arr[] , int arr_size) { int i=0; for( i=0; i< arr_size; i++ ){ if( arr[i*2] ){ efree( arr[i*2]); } } efree(arr); } #define LOOKUP_CLEAN_RETURN(value) array_cleanup(cur_arr, cur_arr_len); return (value) /* {{{ * returns the lookup result to lookup_loc_range_src_php * internal function */ static char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC) { int i = 0; int cur_arr_len = 0; int result = 0; char* lang_tag = NULL; zval** ele_value = NULL; char** cur_arr = NULL; char* cur_loc_range = NULL; char* can_loc_range = NULL; int saved_pos = 0; char* return_value = NULL; cur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *)); /* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */ for(zend_hash_internal_pointer_reset(hash_arr); zend_hash_has_more_elements(hash_arr) == SUCCESS; zend_hash_move_forward(hash_arr)) { if (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) { /* Should never actually fail since the key is known to exist.*/ continue; } if(Z_TYPE_PP(ele_value)!= IS_STRING) { /* element value is not a string */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: locale array element is not a string", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value)); result = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value); cur_arr_len++ ; } /* end of for */ /* Canonicalize array elements */ if(canonicalize) { for(i=0; i<cur_arr_len; i++) { lang_tag = get_icu_value_internal(cur_arr[i*2], LOC_CANONICALIZE_TAG, &result, 0); if(result != 1 || lang_tag == NULL || !lang_tag[0]) { if(lang_tag) { efree(lang_tag); } intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[i*2] = erealloc(cur_arr[i*2], strlen(lang_tag)+1); result = strToMatch(lang_tag, cur_arr[i*2]); efree(lang_tag); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } } } if(canonicalize) { /* Canonicalize the loc_range */ can_loc_range = get_icu_value_internal(loc_range, LOC_CANONICALIZE_TAG, &result , 0); if( result != 1 || can_loc_range == NULL || !can_loc_range[0]) { /* Error */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize loc_range" , 0 TSRMLS_CC ); if(can_loc_range) { efree(can_loc_range); } LOOKUP_CLEAN_RETURN(NULL); } else { loc_range = can_loc_range; } } cur_loc_range = ecalloc(1, strlen(loc_range)+1); /* convert to lower and replace hyphens */ result = strToMatch(loc_range, cur_loc_range); if(can_loc_range) { efree(can_loc_range); } if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } /* Lookup for the lang_tag match */ saved_pos = strlen(cur_loc_range); while(saved_pos > 0) { for(i=0; i< cur_arr_len; i++){ if(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) { /* Match found */ return_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]); efree(cur_loc_range); LOOKUP_CLEAN_RETURN(return_value); } } saved_pos = getStrrtokenPos(cur_loc_range, saved_pos); } /* Match not found */ efree(cur_loc_range); LOOKUP_CLEAN_RETURN(NULL); } /* }}} */ /* {{{ proto string Locale::lookup(array $langtag, string $locale[, bool $canonicalize[, string $default = null]]) * Searchs the items in $langtag for the best match to the language * range */ /* }}} */ /* {{{ proto string locale_lookup(array $langtag, string $locale[, bool $canonicalize[, string $default = null]]) * Searchs the items in $langtag for the best match to the language * range */ PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); } /* }}} */ /* {{{ proto string Locale::acceptFromHttp(string $http_accept) * Tries to find out best available locale based on HTTP �Accept-Language� header */ /* }}} */ /* {{{ proto string locale_accept_from_http(string $http_accept) * Tries to find out best available locale based on HTTP �Accept-Language� header */ PHP_FUNCTION(locale_accept_from_http) { UEnumeration *available; char *http_accept = NULL; int http_accept_len; UErrorCode status = 0; int len; char resultLocale[INTL_MAX_LOCALE_LEN+1]; UAcceptResult outResult; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC ); RETURN_FALSE; } available = ures_openAvailableLocales(NULL, &status); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list"); len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN, &outResult, http_accept, available, &status); uenum_close(available); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale"); if (len < 0 || outResult == ULOC_ACCEPT_FAILED) { RETURN_FALSE; } RETURN_STRINGL(resultLocale, len, 1); } /* }}} */ /* * 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 *can_loc_len */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5082_0
crossvul-cpp_data_bad_289_0
/* * Copyright (C) 1999 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { 2, "Administratively Shutdown"}, { 3, "Peer Unconfigured"}, { 4, "Administratively Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */ /* NLRI "prefix length" from RFC 2858 Section 4. */ ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ /* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits. * RFC 4684 Section 4 defines the layout of "origin AS" and "route * target" fields inside the "prefix" depending on its length. */ if (0 == plen) { /* Without "origin AS", without "route target". */ snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; /* With at least "origin AS", possibly with "route target". */ ND_TCHECK_32BITS(pptr + 1); as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1)); plen-=32; /* adjust prefix length */ if (64 < plen) return -1; /* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 } * and gives the number of octets in the variable-length "route * target" field inside this NLRI "prefix". Look for it. */ memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[5], (plen + 7) / 8); memcpy(&route_target, &pptr[5], (plen + 7) / 8); /* Which specification says to do this? */ if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", asbuf, bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; ND_TCHECK2(tptr[0], 5); tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; tlen = len; while (tlen >= 3) { ND_TCHECK2(tptr[0], 3); type = *tptr; length = EXTRACT_16BITS(tptr+1); tptr += 3; tlen -= 3; ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); if (length < 3) goto trunc; length -= 3; /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length); switch (type) { case BGP_AIGP_TLV: if (length < 8) goto trunc; ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr,"\n\t ", length); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_289_0
crossvul-cpp_data_good_5293_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % 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/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.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/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(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 IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop 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 ReadPSDImage method is: % % Image *ReadPSDImage(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 const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_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=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } CheckNumberCompactPixels; compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q), exception),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* 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 image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD 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 RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(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 inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open 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); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5293_0
crossvul-cpp_data_good_2734_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N GGGG % % P P NN N G % % PPPP N N N G GG % % P N NN G G % % P N N GGG % % % % % % Read/Write Portable Network Graphics Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % November 1997 % % % % % % Copyright 1999-2017 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://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/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.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/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/log.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/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/transform.h" #include "magick/utility.h" #if defined(MAGICKCORE_PNG_DELEGATE) /* Suppress libpng pedantic warnings that were added in * libpng-1.2.41 and libpng-1.4.0. If you are working on * migration to libpng-1.5, remove these defines and then * fix any code that generates warnings. */ /* #define PNG_DEPRECATED Use of this function is deprecated */ /* #define PNG_USE_RESULT The result of this function must be checked */ /* #define PNG_NORETURN This function does not return */ /* #define PNG_ALLOCATED The result of the function is new memory */ /* #define PNG_DEPSTRUCT Access to this struct member is deprecated */ /* PNG_PTR_NORETURN does not work on some platforms, in libpng-1.5.x */ #define PNG_PTR_NORETURN #include "png.h" #include "zlib.h" /* ImageMagick differences */ #define first_scene scene #if PNG_LIBPNG_VER > 10011 /* Optional declarations. Define or undefine them as you like. */ /* #define PNG_DEBUG -- turning this on breaks VisualC compiling */ /* Features under construction. Define these to work on them. */ #undef MNG_OBJECT_BUFFERS #undef MNG_BASI_SUPPORTED #define MNG_COALESCE_LAYERS /* In 5.4.4, this interfered with MMAP'ed files. */ #define MNG_INSERT_LAYERS /* Troublesome, but seem to work as of 5.4.4 */ #if defined(MAGICKCORE_JPEG_DELEGATE) # define JNG_SUPPORTED /* Not finished as of 5.5.2. See "To do" comments. */ #endif #if !defined(RGBColorMatchExact) #define IsPNGColorEqual(color,target) \ (((color).red == (target).red) && \ ((color).green == (target).green) && \ ((color).blue == (target).blue)) #endif /* Table of recognized sRGB ICC profiles */ struct sRGB_info_struct { png_uint_32 len; png_uint_32 crc; png_byte intent; }; const struct sRGB_info_struct sRGB_info[] = { /* ICC v2 perceptual sRGB_IEC61966-2-1_black_scaled.icc */ { 3048, 0x3b8772b9UL, 0}, /* ICC v2 relative sRGB_IEC61966-2-1_no_black_scaling.icc */ { 3052, 0x427ebb21UL, 1}, /* ICC v4 perceptual sRGB_v4_ICC_preference_displayclass.icc */ {60988, 0x306fd8aeUL, 0}, /* ICC v4 perceptual sRGB_v4_ICC_preference.icc perceptual */ {60960, 0xbbef7812UL, 0}, /* HP? sRGB v2 media-relative sRGB_IEC61966-2-1_noBPC.icc */ { 3024, 0x5d5129ceUL, 1}, /* HP-Microsoft sRGB v2 perceptual */ { 3144, 0x182ea552UL, 0}, /* HP-Microsoft sRGB v2 media-relative */ { 3144, 0xf29e526dUL, 1}, /* Facebook's "2012/01/25 03:41:57", 524, "TINYsRGB.icc" */ { 524, 0xd4938c39UL, 0}, /* "2012/11/28 22:35:21", 3212, "Argyll_sRGB.icm") */ { 3212, 0x034af5a1UL, 0}, /* Not recognized */ { 0, 0x00000000UL, 0}, }; /* Macros for left-bit-replication to ensure that pixels * and PixelPackets all have the same image->depth, and for use * in PNG8 quantization. */ /* LBR01: Replicate top bit */ #define LBR01PacketRed(pixelpacket) \ (pixelpacket).red=(ScaleQuantumToChar((pixelpacket).red) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketGreen(pixelpacket) \ (pixelpacket).green=(ScaleQuantumToChar((pixelpacket).green) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketBlue(pixelpacket) \ (pixelpacket).blue=(ScaleQuantumToChar((pixelpacket).blue) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketOpacity(pixelpacket) \ (pixelpacket).opacity=(ScaleQuantumToChar((pixelpacket).opacity) < 0x10 ? \ 0 : QuantumRange); #define LBR01PacketRGB(pixelpacket) \ { \ LBR01PacketRed((pixelpacket)); \ LBR01PacketGreen((pixelpacket)); \ LBR01PacketBlue((pixelpacket)); \ } #define LBR01PacketRGBO(pixelpacket) \ { \ LBR01PacketRGB((pixelpacket)); \ LBR01PacketOpacity((pixelpacket)); \ } #define LBR01PixelRed(pixel) \ (SetPixelRed((pixel), \ ScaleQuantumToChar(GetPixelRed((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelGreen(pixel) \ (SetPixelGreen((pixel), \ ScaleQuantumToChar(GetPixelGreen((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelBlue(pixel) \ (SetPixelBlue((pixel), \ ScaleQuantumToChar(GetPixelBlue((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelOpacity(pixel) \ (SetPixelOpacity((pixel), \ ScaleQuantumToChar(GetPixelOpacity((pixel))) < 0x10 ? \ 0 : QuantumRange)); #define LBR01PixelRGB(pixel) \ { \ LBR01PixelRed((pixel)); \ LBR01PixelGreen((pixel)); \ LBR01PixelBlue((pixel)); \ } #define LBR01PixelRGBO(pixel) \ { \ LBR01PixelRGB((pixel)); \ LBR01PixelOpacity((pixel)); \ } /* LBR02: Replicate top 2 bits */ #define LBR02PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xc0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xc0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xc0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xc0; \ (pixelpacket).opacity=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6))); \ } #define LBR02PacketRGB(pixelpacket) \ { \ LBR02PacketRed((pixelpacket)); \ LBR02PacketGreen((pixelpacket)); \ LBR02PacketBlue((pixelpacket)); \ } #define LBR02PacketRGBO(pixelpacket) \ { \ LBR02PacketRGB((pixelpacket)); \ LBR02PacketOpacity((pixelpacket)); \ } #define LBR02PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xc0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xc0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xc0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02Opacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xc0; \ SetPixelOpacity((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 2) | (lbr_bits >> 4) | (lbr_bits >> 6)))); \ } #define LBR02PixelRGB(pixel) \ { \ LBR02PixelRed((pixel)); \ LBR02PixelGreen((pixel)); \ LBR02PixelBlue((pixel)); \ } #define LBR02PixelRGBO(pixel) \ { \ LBR02PixelRGB((pixel)); \ LBR02Opacity((pixel)); \ } /* LBR03: Replicate top 3 bits (only used with opaque pixels during PNG8 quantization) */ #define LBR03PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xe0; \ (pixelpacket).red=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xe0; \ (pixelpacket).green=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xe0; \ (pixelpacket).blue=ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6))); \ } #define LBR03PacketRGB(pixelpacket) \ { \ LBR03PacketRed((pixelpacket)); \ LBR03PacketGreen((pixelpacket)); \ LBR03PacketBlue((pixelpacket)); \ } #define LBR03PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xe0; \ SetPixelRed((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xe0; \ SetPixelGreen((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelBlue(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelBlue((pixel))) \ & 0xe0; \ SetPixelBlue((pixel), ScaleCharToQuantum( \ (lbr_bits | (lbr_bits >> 3) | (lbr_bits >> 6)))); \ } #define LBR03PixelRGB(pixel) \ { \ LBR03PixelRed((pixel)); \ LBR03PixelGreen((pixel)); \ LBR03PixelBlue((pixel)); \ } /* LBR04: Replicate top 4 bits */ #define LBR04PacketRed(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).red) & 0xf0; \ (pixelpacket).red=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketGreen(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).green) & 0xf0; \ (pixelpacket).green=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketBlue(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).blue) & 0xf0; \ (pixelpacket).blue=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketOpacity(pixelpacket) \ { \ unsigned char lbr_bits=ScaleQuantumToChar((pixelpacket).opacity) & 0xf0; \ (pixelpacket).opacity=ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4))); \ } #define LBR04PacketRGB(pixelpacket) \ { \ LBR04PacketRed((pixelpacket)); \ LBR04PacketGreen((pixelpacket)); \ LBR04PacketBlue((pixelpacket)); \ } #define LBR04PacketRGBO(pixelpacket) \ { \ LBR04PacketRGB((pixelpacket)); \ LBR04PacketOpacity((pixelpacket)); \ } #define LBR04PixelRed(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelRed((pixel))) \ & 0xf0; \ SetPixelRed((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelGreen(pixel) \ { \ unsigned char lbr_bits=ScaleQuantumToChar(GetPixelGreen((pixel)))\ & 0xf0; \ SetPixelGreen((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelBlue(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelBlue((pixel))) & 0xf0; \ SetPixelBlue((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelOpacity(pixel) \ { \ unsigned char lbr_bits= \ ScaleQuantumToChar(GetPixelOpacity((pixel))) & 0xf0; \ SetPixelOpacity((pixel),\ ScaleCharToQuantum((lbr_bits | (lbr_bits >> 4)))); \ } #define LBR04PixelRGB(pixel) \ { \ LBR04PixelRed((pixel)); \ LBR04PixelGreen((pixel)); \ LBR04PixelBlue((pixel)); \ } #define LBR04PixelRGBO(pixel) \ { \ LBR04PixelRGB((pixel)); \ LBR04PixelOpacity((pixel)); \ } /* Establish thread safety. setjmp/longjmp is claimed to be safe on these platforms: setjmp/longjmp is alleged to be unsafe on these platforms: */ #ifdef PNG_SETJMP_SUPPORTED # ifndef IMPNG_SETJMP_IS_THREAD_SAFE # define IMPNG_SETJMP_NOT_THREAD_SAFE # endif # ifdef IMPNG_SETJMP_NOT_THREAD_SAFE static SemaphoreInfo *ping_semaphore = (SemaphoreInfo *) NULL; # endif #endif /* This temporary until I set up malloc'ed object attributes array. Recompile with MNG_MAX_OBJECTS=65536L to avoid this limit but waste more memory. */ #define MNG_MAX_OBJECTS 256 /* If this not defined, spec is interpreted strictly. If it is defined, an attempt will be made to recover from some errors, including o global PLTE too short */ #undef MNG_LOOSE /* Don't try to define PNG_MNG_FEATURES_SUPPORTED here. Make sure it's defined in libpng/pngconf.h, version 1.0.9 or later. It won't work with earlier versions of libpng. From libpng-1.0.3a to libpng-1.0.8, PNG_READ|WRITE_EMPTY_PLTE were used but those have been deprecated in libpng in favor of PNG_MNG_FEATURES_SUPPORTED, so we set them here. PNG_MNG_FEATURES_SUPPORTED is disabled by default in libpng-1.0.9 and will be enabled by default in libpng-1.2.0. */ #ifdef PNG_MNG_FEATURES_SUPPORTED # ifndef PNG_READ_EMPTY_PLTE_SUPPORTED # define PNG_READ_EMPTY_PLTE_SUPPORTED # endif # ifndef PNG_WRITE_EMPTY_PLTE_SUPPORTED # define PNG_WRITE_EMPTY_PLTE_SUPPORTED # endif #endif /* Maximum valid size_t in PNG/MNG chunks is (2^31)-1 This macro is only defined in libpng-1.0.3 and later. Previously it was PNG_MAX_UINT but that was deprecated in libpng-1.2.6 */ #ifndef PNG_UINT_31_MAX #define PNG_UINT_31_MAX (png_uint_32) 0x7fffffffL #endif /* Constant strings for known chunk types. If you need to add a chunk, add a string holding the name here. To make the code more portable, we use ASCII numbers like this, not characters. */ /* until registration of eXIf */ static const png_byte mng_exIf[5]={101, 120, 73, 102, (png_byte) '\0'}; /* after registration of eXIf */ static const png_byte mng_eXIf[5]={101, 88, 73, 102, (png_byte) '\0'}; static const png_byte mng_MHDR[5]={ 77, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_BACK[5]={ 66, 65, 67, 75, (png_byte) '\0'}; static const png_byte mng_BASI[5]={ 66, 65, 83, 73, (png_byte) '\0'}; static const png_byte mng_CLIP[5]={ 67, 76, 73, 80, (png_byte) '\0'}; static const png_byte mng_CLON[5]={ 67, 76, 79, 78, (png_byte) '\0'}; static const png_byte mng_DEFI[5]={ 68, 69, 70, 73, (png_byte) '\0'}; static const png_byte mng_DHDR[5]={ 68, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_DISC[5]={ 68, 73, 83, 67, (png_byte) '\0'}; static const png_byte mng_ENDL[5]={ 69, 78, 68, 76, (png_byte) '\0'}; static const png_byte mng_FRAM[5]={ 70, 82, 65, 77, (png_byte) '\0'}; static const png_byte mng_IEND[5]={ 73, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_IHDR[5]={ 73, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_JHDR[5]={ 74, 72, 68, 82, (png_byte) '\0'}; static const png_byte mng_LOOP[5]={ 76, 79, 79, 80, (png_byte) '\0'}; static const png_byte mng_MAGN[5]={ 77, 65, 71, 78, (png_byte) '\0'}; static const png_byte mng_MEND[5]={ 77, 69, 78, 68, (png_byte) '\0'}; static const png_byte mng_MOVE[5]={ 77, 79, 86, 69, (png_byte) '\0'}; static const png_byte mng_PAST[5]={ 80, 65, 83, 84, (png_byte) '\0'}; static const png_byte mng_PLTE[5]={ 80, 76, 84, 69, (png_byte) '\0'}; static const png_byte mng_SAVE[5]={ 83, 65, 86, 69, (png_byte) '\0'}; static const png_byte mng_SEEK[5]={ 83, 69, 69, 75, (png_byte) '\0'}; static const png_byte mng_SHOW[5]={ 83, 72, 79, 87, (png_byte) '\0'}; static const png_byte mng_TERM[5]={ 84, 69, 82, 77, (png_byte) '\0'}; static const png_byte mng_bKGD[5]={ 98, 75, 71, 68, (png_byte) '\0'}; static const png_byte mng_caNv[5]={ 99, 97, 78, 118, (png_byte) '\0'}; static const png_byte mng_cHRM[5]={ 99, 72, 82, 77, (png_byte) '\0'}; static const png_byte mng_gAMA[5]={103, 65, 77, 65, (png_byte) '\0'}; static const png_byte mng_iCCP[5]={105, 67, 67, 80, (png_byte) '\0'}; static const png_byte mng_nEED[5]={110, 69, 69, 68, (png_byte) '\0'}; static const png_byte mng_pHYg[5]={112, 72, 89, 103, (png_byte) '\0'}; static const png_byte mng_vpAg[5]={118, 112, 65, 103, (png_byte) '\0'}; static const png_byte mng_pHYs[5]={112, 72, 89, 115, (png_byte) '\0'}; static const png_byte mng_sBIT[5]={115, 66, 73, 84, (png_byte) '\0'}; static const png_byte mng_sRGB[5]={115, 82, 71, 66, (png_byte) '\0'}; static const png_byte mng_tRNS[5]={116, 82, 78, 83, (png_byte) '\0'}; #if defined(JNG_SUPPORTED) static const png_byte mng_IDAT[5]={ 73, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAT[5]={ 74, 68, 65, 84, (png_byte) '\0'}; static const png_byte mng_JDAA[5]={ 74, 68, 65, 65, (png_byte) '\0'}; static const png_byte mng_JdAA[5]={ 74, 100, 65, 65, (png_byte) '\0'}; static const png_byte mng_JSEP[5]={ 74, 83, 69, 80, (png_byte) '\0'}; static const png_byte mng_oFFs[5]={111, 70, 70, 115, (png_byte) '\0'}; #endif #if 0 /* Other known chunks that are not yet supported by ImageMagick: */ static const png_byte mng_hIST[5]={104, 73, 83, 84, (png_byte) '\0'}; static const png_byte mng_iTXt[5]={105, 84, 88, 116, (png_byte) '\0'}; static const png_byte mng_sPLT[5]={115, 80, 76, 84, (png_byte) '\0'}; static const png_byte mng_sTER[5]={115, 84, 69, 82, (png_byte) '\0'}; static const png_byte mng_tEXt[5]={116, 69, 88, 116, (png_byte) '\0'}; static const png_byte mng_tIME[5]={116, 73, 77, 69, (png_byte) '\0'}; static const png_byte mng_zTXt[5]={122, 84, 88, 116, (png_byte) '\0'}; #endif typedef struct _MngBox { long left, right, top, bottom; } MngBox; typedef struct _MngPair { volatile long a, b; } MngPair; #ifdef MNG_OBJECT_BUFFERS typedef struct _MngBuffer { size_t height, width; Image *image; png_color plte[256]; int reference_count; unsigned char alpha_sample_depth, compression_method, color_type, concrete, filter_method, frozen, image_type, interlace_method, pixel_sample_depth, plte_length, sample_depth, viewable; } MngBuffer; #endif typedef struct _MngInfo { #ifdef MNG_OBJECT_BUFFERS MngBuffer *ob[MNG_MAX_OBJECTS]; #endif Image * image; RectangleInfo page; int adjoin, #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED bytes_in_read_buffer, found_empty_plte, #endif equal_backgrounds, equal_chrms, equal_gammas, #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) equal_palettes, #endif equal_physs, equal_srgbs, framing_mode, have_global_bkgd, have_global_chrm, have_global_gama, have_global_phys, have_global_sbit, have_global_srgb, have_saved_bkgd_index, have_write_global_chrm, have_write_global_gama, have_write_global_plte, have_write_global_srgb, need_fram, object_id, old_framing_mode, saved_bkgd_index; int new_number_colors; ssize_t image_found, loop_count[256], loop_iteration[256], scenes_found, x_off[MNG_MAX_OBJECTS], y_off[MNG_MAX_OBJECTS]; MngBox clip, frame, image_box, object_clip[MNG_MAX_OBJECTS]; unsigned char /* These flags could be combined into one byte */ exists[MNG_MAX_OBJECTS], frozen[MNG_MAX_OBJECTS], loop_active[256], invisible[MNG_MAX_OBJECTS], viewable[MNG_MAX_OBJECTS]; MagickOffsetType loop_jump[256]; png_colorp global_plte; png_color_8 global_sbit; png_byte #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED read_buffer[8], #endif global_trns[256]; float global_gamma; ChromaticityInfo global_chrm; RenderingIntent global_srgb_intent; unsigned int delay, global_plte_length, global_trns_length, global_x_pixels_per_unit, global_y_pixels_per_unit, mng_width, mng_height, ticks_per_second; MagickBooleanType need_blob; unsigned int IsPalette, global_phys_unit_type, basi_warning, clon_warning, dhdr_warning, jhdr_warning, magn_warning, past_warning, phyg_warning, phys_warning, sbit_warning, show_warning, mng_type, write_mng, write_png_colortype, write_png_depth, write_png_compression_level, write_png_compression_strategy, write_png_compression_filter, write_png8, write_png24, write_png32, write_png48, write_png64; #ifdef MNG_BASI_SUPPORTED size_t basi_width, basi_height; unsigned int basi_depth, basi_color_type, basi_compression_method, basi_filter_type, basi_interlace_method, basi_red, basi_green, basi_blue, basi_alpha, basi_viewable; #endif png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; PixelPacket mng_global_bkgd; /* Added at version 6.6.6-7 */ MagickBooleanType ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, ping_exclude_eXIf, ping_exclude_EXIF, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tRNS, ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, /* Added at version 6.8.5-7 */ ping_preserve_iCCP, /* Added at version 6.8.9-9 */ ping_exclude_tIME; } MngInfo; #endif /* VER */ /* Forward declarations. */ static MagickBooleanType WritePNGImage(const ImageInfo *,Image *); static MagickBooleanType WriteMNGImage(const ImageInfo *,Image *); #if defined(JNG_SUPPORTED) static MagickBooleanType WriteJNGImage(const ImageInfo *,Image *); #endif #if PNG_LIBPNG_VER > 10011 #if (MAGICKCORE_QUANTUM_DEPTH >= 16) static MagickBooleanType LosslessReduceDepthOK(Image *image) { /* Reduce bit depth if it can be reduced losslessly from 16+ to 8. * * This is true if the high byte and the next highest byte of * each sample of the image, the colormap, and the background color * are equal to each other. We check this by seeing if the samples * are unchanged when we scale them down to 8 and back up to Quantum. * * We don't use the method GetImageDepth() because it doesn't check * background and doesn't handle PseudoClass specially. */ #define QuantumToCharToQuantumEqQuantum(quantum) \ ((ScaleCharToQuantum((unsigned char) ScaleQuantumToChar(quantum))) == quantum) MagickBooleanType ok_to_reduce=MagickFalse; if (image->depth >= 16) { const PixelPacket *p; ok_to_reduce= QuantumToCharToQuantumEqQuantum(image->background_color.red) && QuantumToCharToQuantumEqQuantum(image->background_color.green) && QuantumToCharToQuantumEqQuantum(image->background_color.blue) ? MagickTrue : MagickFalse; if (ok_to_reduce != MagickFalse && image->storage_class == PseudoClass) { int indx; for (indx=0; indx < (ssize_t) image->colors; indx++) { ok_to_reduce=( QuantumToCharToQuantumEqQuantum( image->colormap[indx].red) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].green) && QuantumToCharToQuantumEqQuantum( image->colormap[indx].blue)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; } } if ((ok_to_reduce != MagickFalse) && (image->storage_class != PseudoClass)) { ssize_t y; register ssize_t x; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) { ok_to_reduce = MagickFalse; break; } for (x=(ssize_t) image->columns-1; x >= 0; x--) { ok_to_reduce= QuantumToCharToQuantumEqQuantum(GetPixelRed(p)) && QuantumToCharToQuantumEqQuantum(GetPixelGreen(p)) && QuantumToCharToQuantumEqQuantum(GetPixelBlue(p)) ? MagickTrue : MagickFalse; if (ok_to_reduce == MagickFalse) break; p++; } if (x >= 0) break; } } if (ok_to_reduce != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " OK to reduce PNG bit depth to 8 without loss of info"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Not OK to reduce PNG bit depth to 8 without loss of info"); } } return ok_to_reduce; } #endif /* MAGICKCORE_QUANTUM_DEPTH >= 16 */ static const char* PngColorTypeToString(const unsigned int color_type) { const char *result = "Unknown"; switch (color_type) { case PNG_COLOR_TYPE_GRAY: result = "Gray"; break; case PNG_COLOR_TYPE_GRAY_ALPHA: result = "Gray+Alpha"; break; case PNG_COLOR_TYPE_PALETTE: result = "Palette"; break; case PNG_COLOR_TYPE_RGB: result = "RGB"; break; case PNG_COLOR_TYPE_RGB_ALPHA: result = "RGB+Alpha"; break; } return result; } static int Magick_RenderingIntent_to_PNG_RenderingIntent(const RenderingIntent intent) { switch (intent) { case PerceptualIntent: return 0; case RelativeIntent: return 1; case SaturationIntent: return 2; case AbsoluteIntent: return 3; default: return -1; } } static RenderingIntent Magick_RenderingIntent_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return PerceptualIntent; case 1: return RelativeIntent; case 2: return SaturationIntent; case 3: return AbsoluteIntent; default: return UndefinedIntent; } } static const char * Magick_RenderingIntentString_from_PNG_RenderingIntent(const int ping_intent) { switch (ping_intent) { case 0: return "Perceptual Intent"; case 1: return "Relative Intent"; case 2: return "Saturation Intent"; case 3: return "Absolute Intent"; default: return "Undefined Intent"; } } static const char * Magick_ColorType_from_PNG_ColorType(const int ping_colortype) { switch (ping_colortype) { case 0: return "Grayscale"; case 2: return "Truecolor"; case 3: return "Indexed"; case 4: return "GrayAlpha"; case 6: return "RGBA"; default: return "UndefinedColorType"; } } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* MAGICKCORE_PNG_DELEGATE */ /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMNG() returns MagickTrue if the image format type, identified by the % magick string, is MNG. % % The format of the IsMNG method is: % % MagickBooleanType IsMNG(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 IsMNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\212MNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJNG() returns MagickTrue if the image format type, identified by the % magick string, is JNG. % % The format of the IsJNG method is: % % MagickBooleanType IsJNG(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 IsJNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\213JNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNG() returns MagickTrue if the image format type, identified by the % magick string, is PNG. % % The format of the IsPNG method is: % % MagickBooleanType IsPNG(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 IsPNG(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick,"\211PNG\r\n\032\n",8) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_PNG_DELEGATE) #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if (PNG_LIBPNG_VER > 10011) static size_t WriteBlobMSBULong(Image *image,const size_t value) { unsigned char buffer[4]; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; return((size_t) WriteBlob(image,4,buffer)); } static void PNGLong(png_bytep p,png_uint_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGsLong(png_bytep p,png_int_32 value) { *p++=(png_byte) ((value >> 24) & 0xff); *p++=(png_byte) ((value >> 16) & 0xff); *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGShort(png_bytep p,png_uint_16 value) { *p++=(png_byte) ((value >> 8) & 0xff); *p++=(png_byte) (value & 0xff); } static void PNGType(png_bytep p,const png_byte *type) { (void) CopyMagickMemory(p,type,4*sizeof(png_byte)); } static void LogPNGChunk(MagickBooleanType logging, const png_byte *type, size_t length) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing %c%c%c%c chunk, length: %.20g", type[0],type[1],type[2],type[3],(double) length); } #endif /* PNG_LIBPNG_VER > 10011 */ #if defined(__cplusplus) || defined(c_plusplus) } #endif #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNGImage() reads a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image or set of images. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadPNGImage method is: % % Image *ReadPNGImage(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. % % To do, more or less in chronological order (as of version 5.5.2, % November 26, 2002 -- glennrp -- see also "To do" under WriteMNGImage): % % Get 16-bit cheap transparency working. % % (At this point, PNG decoding is supposed to be in full MNG-LC compliance) % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % (At this point, PNG encoding should be in full MNG compliance) % % Provide options for choice of background to use when the MNG BACK % chunk is not present or is not mandatory (i.e., leave transparent, % user specified, MNG BACK, PNG bKGD) % % Implement LOOP/ENDL [done, but could do discretionary loops more % efficiently by linking in the duplicate frames.]. % % Decode and act on the MHDR simplicity profile (offer option to reject % files or attempt to process them anyway when the profile isn't LC or VLC). % % Upgrade to full MNG without Delta-PNG. % % o BACK [done a while ago except for background image ID] % o MOVE [done 15 May 1999] % o CLIP [done 15 May 1999] % o DISC [done 19 May 1999] % o SAVE [partially done 19 May 1999 (marks objects frozen)] % o SEEK [partially done 19 May 1999 (discard function only)] % o SHOW % o PAST % o BASI % o MNG-level tEXt/iTXt/zTXt % o pHYg % o pHYs % o sBIT % o bKGD % o iTXt (wait for libpng implementation). % % Use the scene signature to discover when an identical scene is % being reused, and just point to the original image->exception instead % of storing another set of pixels. This not specific to MNG % but could be applied generally. % % Upgrade to full MNG with Delta-PNG. % % JNG tEXt/iTXt/zTXt % % We will not attempt to read files containing the CgBI chunk. % They are really Xcode files meant for display on the iPhone. % These are not valid PNG files and it is impossible to recover % the original PNG from files that have been converted to Xcode-PNG, % since irretrievable loss of color data has occurred due to the % use of premultiplied alpha. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* This the function that does the actual reading of data. It is the same as the one supplied in libpng, except that it receives the datastream from the ReadBlob() function instead of standard input. */ static void png_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) ReadBlob(image,(size_t) length,data); if (check != length) { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent, "Expected %.20g bytes; found %.20g bytes",(double) length, (double) check); png_warning(png_ptr,msg); png_error(png_ptr,"Read Exception"); } } } #if !defined(PNG_READ_EMPTY_PLTE_SUPPORTED) && \ !defined(PNG_MNG_FEATURES_SUPPORTED) /* We use mng_get_data() instead of png_get_data() if we have a libpng * older than libpng-1.0.3a, which was the first to allow the empty * PLTE, or a newer libpng in which PNG_MNG_FEATURES_SUPPORTED was * ifdef'ed out. Earlier versions would crash if the bKGD chunk was * encountered after an empty PLTE, so we have to look ahead for bKGD * chunks and remove them from the datastream that is passed to libpng, * and store their contents for later use. */ static void mng_get_data(png_structp png_ptr,png_bytep data,png_size_t length) { MngInfo *mng_info; Image *image; png_size_t check; register ssize_t i; i=0; mng_info=(MngInfo *) png_get_io_ptr(png_ptr); image=(Image *) mng_info->image; while (mng_info->bytes_in_read_buffer && length) { data[i]=mng_info->read_buffer[i]; mng_info->bytes_in_read_buffer--; length--; i++; } if (length != 0) { check=(png_size_t) ReadBlob(image,(size_t) length,(char *) data); if (check != length) png_error(png_ptr,"Read Exception"); if (length == 4) { if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 0)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_PLTE,4) == 0) mng_info->found_empty_plte=MagickTrue; if (memcmp(mng_info->read_buffer,mng_IEND,4) == 0) { mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; } } if ((data[0] == 0) && (data[1] == 0) && (data[2] == 0) && (data[3] == 1)) { check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->read_buffer[4]=0; mng_info->bytes_in_read_buffer=4; if (memcmp(mng_info->read_buffer,mng_bKGD,4) == 0) if (mng_info->found_empty_plte) { /* Skip the bKGD data byte and CRC. */ check=(png_size_t) ReadBlob(image,5,(char *) mng_info->read_buffer); check=(png_size_t) ReadBlob(image,(size_t) length, (char *) mng_info->read_buffer); mng_info->saved_bkgd_index=mng_info->read_buffer[0]; mng_info->have_saved_bkgd_index=MagickTrue; mng_info->bytes_in_read_buffer=0; } } } } } #endif static void png_put_data(png_structp png_ptr,png_bytep data,png_size_t length) { Image *image; image=(Image *) png_get_io_ptr(png_ptr); if (length != 0) { png_size_t check; check=(png_size_t) WriteBlob(image,(size_t) length,data); if (check != length) png_error(png_ptr,"WriteBlob Failed"); } } static void png_flush_data(png_structp png_ptr) { (void) png_ptr; } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED static int PalettesAreEqual(Image *a,Image *b) { ssize_t i; if ((a == (Image *) NULL) || (b == (Image *) NULL)) return((int) MagickFalse); if (a->storage_class != PseudoClass || b->storage_class != PseudoClass) return((int) MagickFalse); if (a->colors != b->colors) return((int) MagickFalse); for (i=0; i < (ssize_t) a->colors; i++) { if ((a->colormap[i].red != b->colormap[i].red) || (a->colormap[i].green != b->colormap[i].green) || (a->colormap[i].blue != b->colormap[i].blue)) return((int) MagickFalse); } return((int) MagickTrue); } #endif static void MngInfoDiscardObject(MngInfo *mng_info,int i) { if (i && (i < MNG_MAX_OBJECTS) && (mng_info != (MngInfo *) NULL) && mng_info->exists[i] && !mng_info->frozen[i]) { #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) { if (mng_info->ob[i]->reference_count > 0) mng_info->ob[i]->reference_count--; if (mng_info->ob[i]->reference_count == 0) { if (mng_info->ob[i]->image != (Image *) NULL) mng_info->ob[i]->image=DestroyImage(mng_info->ob[i]->image); mng_info->ob[i]=DestroyString(mng_info->ob[i]); } } mng_info->ob[i]=(MngBuffer *) NULL; #endif mng_info->exists[i]=MagickFalse; mng_info->invisible[i]=MagickFalse; mng_info->viewable[i]=MagickFalse; mng_info->frozen[i]=MagickFalse; mng_info->x_off[i]=0; mng_info->y_off[i]=0; mng_info->object_clip[i].left=0; mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].top=0; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } } static MngInfo *MngInfoFreeStruct(MngInfo *mng_info) { register ssize_t i; if (mng_info == (MngInfo *) NULL) return((MngInfo *) NULL); for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); if (mng_info->global_plte != (png_colorp) NULL) mng_info->global_plte=(png_colorp) RelinquishMagickMemory(mng_info->global_plte); return((MngInfo *) RelinquishMagickMemory(mng_info)); } static MngBox mng_minimum_box(MngBox box1,MngBox box2) { MngBox box; box=box1; if (box.left < box2.left) box.left=box2.left; if (box.top < box2.top) box.top=box2.top; if (box.right > box2.right) box.right=box2.right; if (box.bottom > box2.bottom) box.bottom=box2.bottom; return box; } static MngBox mng_read_box(MngBox previous_box,char delta_type,unsigned char *p) { MngBox box; /* Read clipping boundaries from DEFI, CLIP, FRAM, or PAST chunk. */ box.left=(ssize_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); box.right=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); box.top=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); box.bottom=(ssize_t) ((p[12] << 24) | (p[13] << 16) | (p[14] << 8) | p[15]); if (delta_type != 0) { box.left+=previous_box.left; box.right+=previous_box.right; box.top+=previous_box.top; box.bottom+=previous_box.bottom; } return(box); } static MngPair mng_read_pair(MngPair previous_pair,int delta_type, unsigned char *p) { MngPair pair; /* Read two ssize_ts from CLON, MOVE or PAST chunk */ pair.a=(long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); pair.b=(long) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (delta_type != 0) { pair.a+=previous_pair.a; pair.b+=previous_pair.b; } return(pair); } static long mng_get_long(unsigned char *p) { return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])); } typedef struct _PNGErrorInfo { Image *image; ExceptionInfo *exception; } PNGErrorInfo; static void MagickPNGErrorHandler(png_struct *ping,png_const_charp message) { Image *image; image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s error: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderError, message,"`%s'",image->filename); #if (PNG_LIBPNG_VER < 10500) /* A warning about deprecated use of jmpbuf here is unavoidable if you * are building with libpng-1.4.x and can be ignored. */ longjmp(ping->jmpbuf,1); #else png_longjmp(ping,1); #endif } static void MagickPNGWarningHandler(png_struct *ping,png_const_charp message) { Image *image; if (LocaleCompare(message, "Missing PLTE before tRNS") == 0) png_error(ping, message); image=(Image *) png_get_error_ptr(ping); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " libpng-%s warning: %s", PNG_LIBPNG_VER_STRING,message); (void) ThrowMagickException(&image->exception,GetMagickModule(),CoderWarning, message,"`%s'",image->filename); } #ifdef PNG_USER_MEM_SUPPORTED #if PNG_LIBPNG_VER >= 10400 static png_voidp Magick_png_malloc(png_structp png_ptr,png_alloc_size_t size) #else static png_voidp Magick_png_malloc(png_structp png_ptr,png_size_t size) #endif { (void) png_ptr; return((png_voidp) AcquireMagickMemory((size_t) size)); } /* Free a pointer. It is removed from the list at the same time. */ static png_free_ptr Magick_png_free(png_structp png_ptr,png_voidp ptr) { (void) png_ptr; ptr=RelinquishMagickMemory(ptr); return((png_free_ptr) NULL); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static int Magick_png_read_raw_profile(png_struct *ping,Image *image, const ImageInfo *image_info, png_textp text,int ii) { register ssize_t i; register unsigned char *dp; register png_charp sp; png_uint_32 length, nibbles; StringInfo *profile; const unsigned char unhex[103]={0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1, 2,3,4,5,6,7,8,9,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,10,11,12, 13,14,15}; sp=text[ii].text+1; /* look for newline */ while (*sp != '\n') sp++; /* look for length */ while (*sp == '\0' || *sp == ' ' || *sp == '\n') sp++; length=(png_uint_32) StringToLong(sp); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu",(unsigned long) length); while (*sp != ' ' && *sp != '\n') sp++; /* allocate space */ if (length == 0) { png_warning(ping,"invalid profile length"); return(MagickFalse); } profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { png_warning(ping, "unable to copy profile"); return(MagickFalse); } /* copy profile, skipping white space and column 1 "=" signs */ dp=GetStringInfoDatum(profile); nibbles=length*2; for (i=0; i < (ssize_t) nibbles; i++) { while (*sp < '0' || (*sp > '9' && *sp < 'a') || *sp > 'f') { if (*sp == '\0') { png_warning(ping, "ran out of profile data"); return(MagickFalse); } sp++; } if (i%2 == 0) *dp=(unsigned char) (16*unhex[(int) *sp++]); else (*dp++)+=unhex[(int) *sp++]; } /* We have already read "Raw profile type. */ (void) SetImageProfile(image,&text[ii].key[17],profile); profile=DestroyStringInfo(profile); if (image_info->verbose) (void) printf(" Found a generic profile, type %s\n",&text[ii].key[17]); return MagickTrue; } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) static int read_user_chunk_callback(png_struct *ping, png_unknown_chunkp chunk) { Image *image; /* The unknown chunk structure contains the chunk data: png_byte name[5]; png_byte *data; png_size_t size; Note that libpng has already taken care of the CRC handling. */ LogMagickEvent(CoderEvent,GetMagickModule(), " read_user_chunk: found %c%c%c%c chunk", chunk->name[0],chunk->name[1],chunk->name[2],chunk->name[3]); if (chunk->name[0] == 101 && (chunk->name[1] == 88 || chunk->name[1] == 120 ) && chunk->name[2] == 73 && chunk-> name[3] == 102) { /* process eXIf or exIf chunk */ PNGErrorInfo *error_info; StringInfo *profile; unsigned char *p; png_byte *s; int i; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " recognized eXIf|exIf chunk"); image=(Image *) png_get_user_chunk_ptr(ping); error_info=(PNGErrorInfo *) png_get_error_ptr(ping); profile=BlobToStringInfo((const void *) NULL,chunk->size+6); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(error_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1); } p=GetStringInfoDatum(profile); /* Initialize profile with "Exif\0\0" */ *p++ ='E'; *p++ ='x'; *p++ ='i'; *p++ ='f'; *p++ ='\0'; *p++ ='\0'; /* copy chunk->data to profile */ s=chunk->data; for (i=0; i < (ssize_t) chunk->size; i++) *p++ = *s++; (void) SetImageProfile(image,"exif",profile); return(1); } /* vpAg (deprecated, replaced by caNv) */ if (chunk->name[0] == 118 && chunk->name[1] == 112 && chunk->name[2] == 65 && chunk->name[3] == 103) { /* recognized vpAg */ if (chunk->size != 9) return(-1); /* Error return */ if (chunk->data[8] != 0) return(0); /* ImageMagick requires pixel units */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); return(1); } /* caNv */ if (chunk->name[0] == 99 && chunk->name[1] == 97 && chunk->name[2] == 78 && chunk->name[3] == 118) { /* recognized caNv */ if (chunk->size != 16) return(-1); /* Error return */ image=(Image *) png_get_user_chunk_ptr(ping); image->page.width=(size_t) ((chunk->data[0] << 24) | (chunk->data[1] << 16) | (chunk->data[2] << 8) | chunk->data[3]); image->page.height=(size_t) ((chunk->data[4] << 24) | (chunk->data[5] << 16) | (chunk->data[6] << 8) | chunk->data[7]); image->page.x=(size_t) ((chunk->data[8] << 24) | (chunk->data[9] << 16) | (chunk->data[10] << 8) | chunk->data[11]); image->page.y=(size_t) ((chunk->data[12] << 24) | (chunk->data[13] << 16) | (chunk->data[14] << 8) | chunk->data[15]); /* Return one of the following: */ /* return(-n); chunk had an error */ /* return(0); did not recognize */ /* return(n); success */ return(1); } return(0); /* Did not recognize */ } #endif #if defined(PNG_tIME_SUPPORTED) static void read_tIME_chunk(Image *image,png_struct *ping,png_info *info) { png_timep time; if (png_get_tIME(ping,info,&time)) { char timestamp[21]; FormatLocaleString(timestamp,21,"%04d-%02d-%02dT%02d:%02d:%02dZ", time->year,time->month,time->day,time->hour,time->minute,time->second); SetImageProperty(image,"png:tIME",timestamp); } } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOnePNGImage() reads a Portable Network Graphics (PNG) image file % (minus the 8-byte signature) 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 ReadOnePNGImage method is: % % Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { /* Read one PNG image */ /* To do: Read the tEXt/Creation Time chunk into the date:create property */ Image *image; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; int intent, /* "PNG Rendering intent", which is ICC intent + 1 */ num_raw_profiles, num_text, num_text_total, num_passes, number_colors, pass, ping_bit_depth, ping_color_type, ping_file_depth, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans, unit_type; double file_gamma; LongPixelPacket transparent_color; MagickBooleanType logging, ping_found_cHRM, ping_found_gAMA, ping_found_iCCP, ping_found_sRGB, ping_found_sRGB_cHRM, ping_preserve_iCCP, status; MemoryInfo *volatile pixel_info; png_bytep ping_trans_alpha; png_color_16p ping_background, ping_trans_color; png_info *end_info, *ping_info; png_struct *ping; png_textp text; png_uint_32 ping_height, ping_width, x_resolution, y_resolution; ssize_t ping_rowbytes, y; register unsigned char *p; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; size_t length, row_offset; ssize_t j; unsigned char *ping_pixels; #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED png_byte unused_chunks[]= { 104, 73, 83, 84, (png_byte) '\0', /* hIST */ 105, 84, 88, 116, (png_byte) '\0', /* iTXt */ 112, 67, 65, 76, (png_byte) '\0', /* pCAL */ 115, 67, 65, 76, (png_byte) '\0', /* sCAL */ 115, 80, 76, 84, (png_byte) '\0', /* sPLT */ #if !defined(PNG_tIME_SUPPORTED) 116, 73, 77, 69, (png_byte) '\0', /* tIME */ #endif #ifdef PNG_APNG_SUPPORTED /* libpng was built with APNG patch; */ /* ignore the APNG chunks */ 97, 99, 84, 76, (png_byte) '\0', /* acTL */ 102, 99, 84, 76, (png_byte) '\0', /* fcTL */ 102, 100, 65, 84, (png_byte) '\0', /* fdAT */ #endif }; #endif /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,32); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,32); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOnePNGImage()\n" " IM version = %s\n" " Libpng version = %s", im_vers, libpng_vers); if (logging != MagickFalse) { if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif #if (PNG_LIBPNG_VER >= 10400) # ifndef PNG_TRANSFORM_GRAY_TO_RGB /* Added at libpng-1.4.0beta67 */ if (image_info->verbose) { printf("Your PNG library (libpng-%s) is an old beta version.\n", PNG_LIBPNG_VER_STRING); printf("Please update it.\n"); } # endif #endif image=mng_info->image; if (logging != MagickFalse) { (void)LogMagickEvent(CoderEvent,GetMagickModule(), " Before reading:\n" " image->matte=%d\n" " image->rendering_intent=%d\n" " image->colorspace=%d\n" " image->gamma=%f", (int) image->matte, (int) image->rendering_intent, (int) image->colorspace, image->gamma); } intent=Magick_RenderingIntent_to_PNG_RenderingIntent(image->rendering_intent); /* Set to an out-of-range color unless tRNS chunk is present */ transparent_color.red=65537; transparent_color.green=65537; transparent_color.blue=65537; transparent_color.opacity=65537; number_colors=0; num_text = 0; num_text_total = 0; num_raw_profiles = 0; ping_found_cHRM = MagickFalse; ping_found_gAMA = MagickFalse; ping_found_iCCP = MagickFalse; ping_found_sRGB = MagickFalse; ping_found_sRGB_cHRM = MagickFalse; ping_preserve_iCCP = MagickFalse; /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_read_struct_2(PNG_LIBPNG_VER_STRING, image, MagickPNGErrorHandler,MagickPNGWarningHandler, NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_read_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_read_struct(&ping,(png_info **) NULL,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } end_info=png_create_info_struct(ping); if (end_info == (png_info *) NULL) { png_destroy_read_struct(&ping,&ping_info,(png_info **) NULL); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG image is corrupt. */ png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() with error."); if (image != (Image *) NULL) InheritException(exception,&image->exception); return(GetFirstImageInList(image)); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for reading. */ mng_info->image_found++; png_set_sig_bytes(ping,8); if (LocaleCompare(image_info->magick,"MNG") == 0) { #if defined(PNG_MNG_FEATURES_SUPPORTED) (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); png_set_read_fn(ping,image,png_get_data); #else #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) png_permit_empty_plte(ping,MagickTrue); png_set_read_fn(ping,image,png_get_data); #else mng_info->image=image; mng_info->bytes_in_read_buffer=0; mng_info->found_empty_plte=MagickFalse; mng_info->have_saved_bkgd_index=MagickFalse; png_set_read_fn(ping,mng_info,mng_get_data); #endif #endif } else png_set_read_fn(ping,image,png_get_data); { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",value) == MagickFalse) { value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) ping_preserve_iCCP=MagickTrue; #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) /* Don't let libpng check for ICC/sRGB profile because we're going * to do that anyway. This feature was added at libpng-1.6.12. * If logging, go ahead and check and issue a warning as appropriate. */ if (logging == MagickFalse) png_set_option(ping, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) else { /* Ignore the iCCP chunk */ png_set_keep_unknown_chunks(ping, 1, mng_iCCP, 1); } #endif } #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* Ignore unused chunks and all unknown chunks except for exIf, caNv, and vpAg */ # if PNG_LIBPNG_VER < 10700 /* Avoid libpng16 warning */ png_set_keep_unknown_chunks(ping, 2, NULL, 0); # else png_set_keep_unknown_chunks(ping, 1, NULL, 0); # endif png_set_keep_unknown_chunks(ping, 2, mng_exIf, 1); png_set_keep_unknown_chunks(ping, 2, mng_caNv, 1); png_set_keep_unknown_chunks(ping, 2, mng_vpAg, 1); png_set_keep_unknown_chunks(ping, 1, unused_chunks, (int)sizeof(unused_chunks)/5); /* Callback for other unknown chunks */ png_set_read_user_chunk_fn(ping, image, read_user_chunk_callback); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED #if (PNG_LIBPNG_VER >= 10400) /* Limit the size of the chunk storage cache used for sPLT, text, * and unknown chunks. */ png_set_chunk_cache_max(ping, 32767); #endif #endif #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature */ png_set_check_for_invalid_index (ping, 0); #endif #if (PNG_LIBPNG_VER < 10400) # if defined(PNG_USE_PNGGCCRD) && defined(PNG_ASSEMBLER_CODE_SUPPORTED) && \ (PNG_LIBPNG_VER >= 10200) && (PNG_LIBPNG_VER < 10220) && defined(__i386__) /* Disable thread-unsafe features of pnggccrd */ if (png_access_version_number() >= 10200) { png_uint_32 mmx_disable_mask=0; png_uint_32 asm_flags; mmx_disable_mask |= ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \ | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \ | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \ | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH ); asm_flags=png_get_asm_flags(ping); png_set_asm_flags(ping, asm_flags & ~mmx_disable_mask); } # endif #endif png_read_info(ping,ping_info); /* Read and check IHDR chunk data */ png_get_IHDR(ping,ping_info,&ping_width,&ping_height, &ping_bit_depth,&ping_color_type, &ping_interlace_method,&ping_compression_method, &ping_filter_method); ping_file_depth = ping_bit_depth; /* Swap bytes if requested */ if (ping_file_depth == 16) { const char *value; value=GetImageOption(image_info,"png:swap-bytes"); if (value == NULL) value=GetImageArtifact(image,"png:swap-bytes"); if (value != NULL) png_set_swap(ping); } /* Save bit-depth and color-type in case we later want to write a PNG00 */ { char msg[MaxTextExtent]; (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_color_type); (void) SetImageProperty(image,"png:IHDR.color-type-orig",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_bit_depth); (void) SetImageProperty(image,"png:IHDR.bit-depth-orig",msg); } (void) png_get_tRNS(ping, ping_info, &ping_trans_alpha, &ping_num_trans, &ping_trans_color); (void) png_get_bKGD(ping, ping_info, &ping_background); if (ping_bit_depth < 8) { png_set_packing(ping); ping_bit_depth = 8; } image->depth=ping_bit_depth; image->depth=GetImageQuantumDepth(image,MagickFalse); image->interlace=ping_interlace_method != 0 ? PNGInterlace : NoInterlace; if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { image->rendering_intent=UndefinedIntent; intent=Magick_RenderingIntent_to_PNG_RenderingIntent(UndefinedIntent); (void) ResetMagickMemory(&image->chromaticity,0, sizeof(image->chromaticity)); } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG width: %.20g, height: %.20g\n" " PNG color_type: %d, bit_depth: %d\n" " PNG compression_method: %d\n" " PNG interlace_method: %d, filter_method: %d", (double) ping_width, (double) ping_height, ping_color_type, ping_bit_depth, ping_compression_method, ping_interlace_method,ping_filter_method); } if (png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_gAMA)) { ping_found_gAMA=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG gAMA chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { ping_found_cHRM=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG cHRM chunk."); } if (ping_found_iCCP != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { ping_found_sRGB=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG sRGB chunk."); } #ifdef PNG_READ_iCCP_SUPPORTED if (ping_found_iCCP !=MagickTrue && ping_found_sRGB != MagickTrue && png_get_valid(ping,ping_info, PNG_INFO_iCCP)) { ping_found_iCCP=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found PNG iCCP chunk."); } if (png_get_valid(ping,ping_info,PNG_INFO_iCCP)) { int compression; #if (PNG_LIBPNG_VER < 10500) png_charp info; #else png_bytep info; #endif png_charp name; png_uint_32 profile_length; (void) png_get_iCCP(ping,ping_info,&name,(int *) &compression,&info, &profile_length); if (profile_length != 0) { StringInfo *profile; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG iCCP chunk."); profile=BlobToStringInfo(info,profile_length); if (profile == (StringInfo *) NULL) { png_warning(ping, "ICC profile is NULL"); profile=DestroyStringInfo(profile); } else { if (ping_preserve_iCCP == MagickFalse) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } break; } } } if (sRGB_info[icheck].len == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); (void) SetImageProfile(image,"icc",profile); } } else /* Preserve-iCCP */ { (void) SetImageProfile(image,"icc",profile); } profile=DestroyStringInfo(profile); } } } #endif #if defined(PNG_READ_sRGB_SUPPORTED) { if (ping_found_iCCP==MagickFalse && png_get_valid(ping,ping_info, PNG_INFO_sRGB)) { if (png_get_sRGB(ping,ping_info,&intent)) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (intent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG sRGB chunk: rendering_intent: %d",intent); } } else if (mng_info->have_global_srgb) { if (image->rendering_intent == UndefinedIntent) image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent (mng_info->global_srgb_intent); } } #endif { if (!png_get_gAMA(ping,ping_info,&file_gamma)) if (mng_info->have_global_gama) png_set_gAMA(ping,ping_info,mng_info->global_gamma); if (png_get_gAMA(ping,ping_info,&file_gamma)) { image->gamma=(float) file_gamma; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG gAMA chunk: gamma: %f",file_gamma); } } if (!png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { if (mng_info->have_global_chrm != MagickFalse) { (void) png_set_cHRM(ping,ping_info, mng_info->global_chrm.white_point.x, mng_info->global_chrm.white_point.y, mng_info->global_chrm.red_primary.x, mng_info->global_chrm.red_primary.y, mng_info->global_chrm.green_primary.x, mng_info->global_chrm.green_primary.y, mng_info->global_chrm.blue_primary.x, mng_info->global_chrm.blue_primary.y); } } if (png_get_valid(ping,ping_info,PNG_INFO_cHRM)) { (void) png_get_cHRM(ping,ping_info, &image->chromaticity.white_point.x, &image->chromaticity.white_point.y, &image->chromaticity.red_primary.x, &image->chromaticity.red_primary.y, &image->chromaticity.green_primary.x, &image->chromaticity.green_primary.y, &image->chromaticity.blue_primary.x, &image->chromaticity.blue_primary.y); ping_found_cHRM=MagickTrue; if (image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f) ping_found_sRGB_cHRM=MagickTrue; } if (image->rendering_intent != UndefinedIntent) { if (ping_found_sRGB != MagickTrue && (ping_found_gAMA != MagickTrue || (image->gamma > .45 && image->gamma < .46)) && (ping_found_cHRM != MagickTrue || ping_found_sRGB_cHRM != MagickFalse) && ping_found_iCCP != MagickTrue) { png_set_sRGB(ping,ping_info, Magick_RenderingIntent_to_PNG_RenderingIntent (image->rendering_intent)); file_gamma=1.000f/2.200f; ping_found_sRGB=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting sRGB as if in input"); } } #if defined(PNG_oFFs_SUPPORTED) if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { image->page.x=(ssize_t) png_get_x_offset_pixels(ping, ping_info); image->page.y=(ssize_t) png_get_y_offset_pixels(ping, ping_info); if (logging != MagickFalse) if (image->page.x || image->page.y) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG oFFs chunk: x: %.20g, y: %.20g.",(double) image->page.x,(double) image->page.y); } #endif #if defined(PNG_pHYs_SUPPORTED) if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { if (mng_info->have_global_phys) { png_set_pHYs(ping,ping_info, mng_info->global_x_pixels_per_unit, mng_info->global_y_pixels_per_unit, mng_info->global_phys_unit_type); } } x_resolution=0; y_resolution=0; unit_type=0; if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { /* Set image resolution. */ (void) png_get_pHYs(ping,ping_info,&x_resolution,&y_resolution, &unit_type); image->x_resolution=(double) x_resolution; image->y_resolution=(double) y_resolution; if (unit_type == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=(double) x_resolution/100.0; image->y_resolution=(double) y_resolution/100.0; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) x_resolution,(double) y_resolution,unit_type); } #endif if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); if ((number_colors == 0) && ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)) { if (mng_info->global_plte_length) { png_set_PLTE(ping,ping_info,mng_info->global_plte, (int) mng_info->global_plte_length); if (!png_get_valid(ping,ping_info,PNG_INFO_tRNS)) if (mng_info->global_trns_length) { if (mng_info->global_trns_length > mng_info->global_plte_length) { png_warning(ping, "global tRNS has more entries than global PLTE"); } else { png_set_tRNS(ping,ping_info,mng_info->global_trns, (int) mng_info->global_trns_length,NULL); } } #ifdef PNG_READ_bKGD_SUPPORTED if ( #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED mng_info->have_saved_bkgd_index || #endif png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { png_color_16 background; #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED if (mng_info->have_saved_bkgd_index) background.index=mng_info->saved_bkgd_index; #endif if (png_get_valid(ping, ping_info, PNG_INFO_bKGD)) background.index=ping_background->index; background.red=(png_uint_16) mng_info->global_plte[background.index].red; background.green=(png_uint_16) mng_info->global_plte[background.index].green; background.blue=(png_uint_16) mng_info->global_plte[background.index].blue; background.gray=(png_uint_16) mng_info->global_plte[background.index].green; png_set_bKGD(ping,ping_info,&background); } #endif } else png_error(ping,"No global PLTE in file"); } } #ifdef PNG_READ_bKGD_SUPPORTED if (mng_info->have_global_bkgd && (!png_get_valid(ping,ping_info,PNG_INFO_bKGD))) image->background_color=mng_info->mng_global_bkgd; if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { unsigned int bkgd_scale; /* Set image background color. * Scale background components to 16-bit, then scale * to quantum depth */ bkgd_scale = 1; if (ping_file_depth == 1) bkgd_scale = 255; else if (ping_file_depth == 2) bkgd_scale = 85; else if (ping_file_depth == 4) bkgd_scale = 17; if (ping_file_depth <= 8) bkgd_scale *= 257; ping_background->red *= bkgd_scale; ping_background->green *= bkgd_scale; ping_background->blue *= bkgd_scale; if (logging != MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG bKGD chunk, raw ping_background=(%d,%d,%d).\n" " bkgd_scale=%d. ping_background=(%d,%d,%d).", ping_background->red,ping_background->green, ping_background->blue, bkgd_scale,ping_background->red, ping_background->green,ping_background->blue); } image->background_color.red= ScaleShortToQuantum(ping_background->red); image->background_color.green= ScaleShortToQuantum(ping_background->green); image->background_color.blue= ScaleShortToQuantum(ping_background->blue); image->background_color.opacity=OpaqueOpacity; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->background_color=(%.20g,%.20g,%.20g).", (double) image->background_color.red, (double) image->background_color.green, (double) image->background_color.blue); } #endif /* PNG_READ_bKGD_SUPPORTED */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { /* Image has a tRNS chunk. */ int max_sample; size_t one=1; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG tRNS chunk."); max_sample = (int) ((one << ping_file_depth) - 1); if ((ping_color_type == PNG_COLOR_TYPE_GRAY && (int)ping_trans_color->gray > max_sample) || (ping_color_type == PNG_COLOR_TYPE_RGB && ((int)ping_trans_color->red > max_sample || (int)ping_trans_color->green > max_sample || (int)ping_trans_color->blue > max_sample))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Ignoring PNG tRNS chunk with out-of-range sample."); png_free_data(ping, ping_info, PNG_FREE_TRNS, 0); png_set_invalid(ping,ping_info,PNG_INFO_tRNS); image->matte=MagickFalse; } else { int scale_to_short; scale_to_short = 65535L/((1UL << ping_file_depth)-1); /* Scale transparent_color to short */ transparent_color.red= scale_to_short*ping_trans_color->red; transparent_color.green= scale_to_short*ping_trans_color->green; transparent_color.blue= scale_to_short*ping_trans_color->blue; transparent_color.opacity= scale_to_short*ping_trans_color->gray; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Raw tRNS graylevel = %d, scaled graylevel = %d.", ping_trans_color->gray,transparent_color.opacity); } transparent_color.red=transparent_color.opacity; transparent_color.green=transparent_color.opacity; transparent_color.blue=transparent_color.opacity; } } } #if defined(PNG_READ_sBIT_SUPPORTED) if (mng_info->have_global_sbit) { if (!png_get_valid(ping,ping_info,PNG_INFO_sBIT)) png_set_sBIT(ping,ping_info,&mng_info->global_sbit); } #endif num_passes=png_set_interlace_handling(ping); png_read_update_info(ping,ping_info); ping_rowbytes=png_get_rowbytes(ping,ping_info); /* Initialize image structure. */ mng_info->image_box.left=0; mng_info->image_box.right=(ssize_t) ping_width; mng_info->image_box.top=0; mng_info->image_box.bottom=(ssize_t) ping_height; if (mng_info->mng_type == 0) { mng_info->mng_width=ping_width; mng_info->mng_height=ping_height; mng_info->frame=mng_info->image_box; mng_info->clip=mng_info->image_box; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } image->compression=ZipCompression; image->columns=ping_width; image->rows=ping_height; if (((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || ((int) ping_bit_depth < 16 && (int) ping_color_type == PNG_COLOR_TYPE_GRAY)) { size_t one; image->storage_class=PseudoClass; one=1; image->colors=one << ping_file_depth; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->colors > 256) image->colors=256; #else if (image->colors > 65536L) image->colors=65536L; #endif if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); image->colors=(size_t) number_colors; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG PLTE chunk: number_colors: %d.",number_colors); } } if (image->storage_class == PseudoClass) { /* Initialize image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) png_error(ping,"Memory allocation failed"); if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette; (void) png_get_PLTE(ping,ping_info,&palette,&number_colors); for (i=0; i < (ssize_t) number_colors; i++) { image->colormap[i].red=ScaleCharToQuantum(palette[i].red); image->colormap[i].green=ScaleCharToQuantum(palette[i].green); image->colormap[i].blue=ScaleCharToQuantum(palette[i].blue); } for ( ; i < (ssize_t) image->colors; i++) { image->colormap[i].red=0; image->colormap[i].green=0; image->colormap[i].blue=0; } } else { Quantum scale; scale = 65535/((1UL << ping_file_depth)-1); #if (MAGICKCORE_QUANTUM_DEPTH > 16) scale = ScaleShortToQuantum(scale); #endif for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(Quantum) (i*scale); image->colormap[i].green=(Quantum) (i*scale); image->colormap[i].blue=(Quantum) (i*scale); } } } /* Set some properties for reporting by "identify" */ { char msg[MaxTextExtent]; /* encode ping_width, ping_height, ping_file_depth, ping_color_type, ping_interlace_method in value */ (void) FormatLocaleString(msg,MaxTextExtent, "%d, %d",(int) ping_width, (int) ping_height); (void) SetImageProperty(image,"png:IHDR.width,height",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d",(int) ping_file_depth); (void) SetImageProperty(image,"png:IHDR.bit_depth",msg); (void) FormatLocaleString(msg,MaxTextExtent,"%d (%s)", (int) ping_color_type, Magick_ColorType_from_PNG_ColorType((int)ping_color_type)); (void) SetImageProperty(image,"png:IHDR.color_type",msg); if (ping_interlace_method == 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Not interlaced)", (int) ping_interlace_method); } else if (ping_interlace_method == 1) { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Adam7 method)", (int) ping_interlace_method); } else { (void) FormatLocaleString(msg,MaxTextExtent,"%d (Unknown method)", (int) ping_interlace_method); } (void) SetImageProperty(image,"png:IHDR.interlace_method",msg); if (number_colors != 0) { (void) FormatLocaleString(msg,MaxTextExtent,"%d", (int) number_colors); (void) SetImageProperty(image,"png:PLTE.number_colors",msg); } } #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,ping_info); #endif /* Read image scanlines. */ if (image->delay != 0) mng_info->scenes_found++; if ((mng_info->mng_type == 0 && (image->ping != MagickFalse)) || ( (image_info->number_scenes != 0) && (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)))) { /* This happens later in non-ping decodes */ if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) image->storage_class=DirectClass; image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping PNG image data for scene %.20g",(double) mng_info->scenes_found-1); png_destroy_read_struct(&ping,&ping_info,&end_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()."); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG IDAT chunk(s)"); if (num_passes > 1) pixel_info=AcquireVirtualMemory(image->rows,ping_rowbytes* sizeof(*ping_pixels)); else pixel_info=AcquireVirtualMemory(ping_rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Memory allocation failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting PNG pixels to pixel packets"); /* Convert PNG pixels to pixel packets. */ { MagickBooleanType found_transparent_pixel; found_transparent_pixel=MagickFalse; if (image->storage_class == DirectClass) { QuantumInfo *quantum_info; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Failed to allocate quantum_info"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (pass=0; pass < num_passes; pass++) { /* Convert image to DirectClass pixel packets. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; for (y=0; y < (ssize_t) image->rows; y++) { if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; else { if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayAlphaQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBAQuantum,ping_pixels+row_offset,exception); else if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, IndexQuantum,ping_pixels+row_offset,exception); else /* ping_color_type == PNG_COLOR_TYPE_RGB */ (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, RGBQuantum,ping_pixels+row_offset,exception); } if (found_transparent_pixel == MagickFalse) { /* Is there a transparent pixel in the row? */ if (y== 0 && logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Looking for cheap transparent pixel"); for (x=(ssize_t) image->columns-1; x >= 0; x--) { if ((ping_color_type == PNG_COLOR_TYPE_RGBA || ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) && (GetPixelOpacity(q) != OpaqueOpacity)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } if ((ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_GRAY) && (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ...got one."); found_transparent_pixel = MagickTrue; break; } q++; } } if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag, (MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); } else /* image->storage_class != DirectClass */ for (pass=0; pass < num_passes; pass++) { Quantum *quantum_scanline; register Quantum *r; /* Convert grayscale image to PseudoClass pixel packets. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Converting grayscale pixels to pixel packets"); image->matte=ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ? MagickTrue : MagickFalse; quantum_scanline=(Quantum *) AcquireQuantumMemory(image->columns, (image->matte ? 2 : 1)*sizeof(*quantum_scanline)); if (quantum_scanline == (Quantum *) NULL) png_error(ping,"Memory allocation failed"); for (y=0; y < (ssize_t) image->rows; y++) { Quantum alpha; if (num_passes > 1) row_offset=ping_rowbytes*y; else row_offset=0; png_read_row(ping,ping_pixels+row_offset,NULL); if (pass < num_passes-1) continue; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=ping_pixels+row_offset; r=quantum_scanline; switch (ping_bit_depth) { case 8: { if (ping_color_type == 4) for (x=(ssize_t) image->columns-1; x >= 0; x--) { *r++=*p++; /* In image.h, OpaqueOpacity is 0 * TransparentOpacity is QuantumRange * In a PNG datastream, Opaque is QuantumRange * and Transparent is 0. */ alpha=ScaleCharToQuantum((unsigned char)*p++); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } else for (x=(ssize_t) image->columns-1; x >= 0; x--) *r++=*p++; break; } case 16: { for (x=(ssize_t) image->columns-1; x >= 0; x--) { #if (MAGICKCORE_QUANTUM_DEPTH >= 16) size_t quantum; if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); *r=ScaleShortToQuantum(quantum); r++; if (ping_color_type == 4) { if (image->colors > 256) quantum=((*p++) << 8); else quantum=0; quantum|=(*p++); alpha=ScaleShortToQuantum(quantum); SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; q++; } #else /* MAGICKCORE_QUANTUM_DEPTH == 8 */ *r++=(*p++); p++; /* strip low byte */ if (ping_color_type == 4) { alpha=*p++; SetPixelAlpha(q,alpha); if (alpha != QuantumRange-OpaqueOpacity) found_transparent_pixel = MagickTrue; p++; q++; } #endif } break; } default: break; } /* Transfer image scanline. */ r=quantum_scanline; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*r++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (num_passes == 1) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (num_passes != 1) { status=SetImageProgress(image,LoadImageTag,pass,num_passes); if (status == MagickFalse) break; } quantum_scanline=(Quantum *) RelinquishMagickMemory(quantum_scanline); } image->matte=found_transparent_pixel; if (logging != MagickFalse) { if (found_transparent_pixel != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found transparent pixel"); else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No transparent pixel was found"); ping_color_type&=0x03; } } } if (image->storage_class == PseudoClass) { MagickBooleanType matte; matte=image->matte; image->matte=MagickFalse; (void) SyncImage(image); image->matte=matte; } png_read_end(ping,end_info); if (image_info->number_scenes != 0 && mng_info->scenes_found-1 < (ssize_t) image_info->first_scene && image->delay != 0) { png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); image->colors=2; (void) SetImageBackgroundColor(image); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage() early."); return(image); } if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) { ClassType storage_class; /* Image has a transparent background. */ storage_class=image->storage_class; image->matte=MagickTrue; /* Balfour fix from imagemagick discourse server, 5 Feb 2010 */ if (storage_class == PseudoClass) { if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { for (x=0; x < ping_num_trans; x++) { image->colormap[x].opacity = ScaleCharToQuantum((unsigned char)(255-ping_trans_alpha[x])); } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY) { for (x=0; x < (int) image->colors; x++) { if (ScaleQuantumToShort(image->colormap[x].red) == transparent_color.opacity) { image->colormap[x].opacity = (Quantum) TransparentOpacity; } } } (void) SyncImage(image); } #if 1 /* Should have already been done above, but glennrp problem P10 * needs this. */ else { for (y=0; y < (ssize_t) image->rows; y++) { image->storage_class=storage_class; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); /* Caution: on a Q8 build, this does not distinguish between * 16-bit colors that differ only in the low byte */ for (x=(ssize_t) image->columns-1; x >= 0; x--) { if (ScaleQuantumToShort(GetPixelRed(q)) == transparent_color.red && ScaleQuantumToShort(GetPixelGreen(q)) == transparent_color.green && ScaleQuantumToShort(GetPixelBlue(q)) == transparent_color.blue) { SetPixelOpacity(q,TransparentOpacity); } #if 0 /* I have not found a case where this is needed. */ else { SetPixelOpacity(q)=(Quantum) OpaqueOpacity; } #endif q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif image->storage_class=DirectClass; } if ((ping_color_type == PNG_COLOR_TYPE_GRAY) || (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) { double image_gamma = image->gamma; (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->gamma=%f",(float) image_gamma); if (image_gamma > 0.75) { /* Set image->rendering_intent to Undefined, * image->colorspace to GRAY, and reset image->chromaticity. */ image->intensity = Rec709LuminancePixelIntensityMethod; SetImageColorspace(image,GRAYColorspace); } else { RenderingIntent save_rendering_intent = image->rendering_intent; ChromaticityInfo save_chromaticity = image->chromaticity; SetImageColorspace(image,GRAYColorspace); image->rendering_intent = save_rendering_intent; image->chromaticity = save_chromaticity; } image->gamma = image_gamma; } (void)LogMagickEvent(CoderEvent,GetMagickModule(), " image->colorspace=%d",(int) image->colorspace); for (j = 0; j < 2; j++) { if (j == 0) status = png_get_text(ping,ping_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; else status = png_get_text(ping,end_info,&text,&num_text) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) for (i=0; i < (ssize_t) num_text; i++) { /* Check for a profile */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading PNG text chunk"); if (strlen(text[i].key) > 16 && memcmp(text[i].key, "Raw profile type ",17) == 0) { const char *value; value=GetImageOption(image_info,"profile:skip"); if (IsOptionMember(text[i].key+17,value) == MagickFalse) { (void) Magick_png_read_raw_profile(ping,image,image_info,text, (int) i); num_raw_profiles++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Read raw profile %s",text[i].key+17); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping raw profile %s",text[i].key+17); } } else { char *value; length=text[i].text_length; value=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*value)); if (value == (char *) NULL) png_error(ping,"Memory allocation failed"); *value='\0'; (void) ConcatenateMagickString(value,text[i].text,length+2); /* Don't save "density" or "units" property if we have a pHYs * chunk */ if (!png_get_valid(ping,ping_info,PNG_INFO_pHYs) || (LocaleCompare(text[i].key,"density") != 0 && LocaleCompare(text[i].key,"units") != 0)) (void) SetImageProperty(image,text[i].key,value); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " length: %lu\n" " Keyword: %s", (unsigned long) length, text[i].key); } value=DestroyString(value); } } num_text_total += num_text; } #ifdef MNG_OBJECT_BUFFERS /* Store the object if necessary. */ if (object_id && !mng_info->frozen[object_id]) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) { /* create a new object buffer. */ mng_info->ob[object_id]=(MngBuffer *) AcquireMagickMemory(sizeof(MngBuffer)); if (mng_info->ob[object_id] != (MngBuffer *) NULL) { mng_info->ob[object_id]->image=(Image *) NULL; mng_info->ob[object_id]->reference_count=1; } } if ((mng_info->ob[object_id] == (MngBuffer *) NULL) || mng_info->ob[object_id]->frozen) { if (mng_info->ob[object_id] == (MngBuffer *) NULL) png_error(ping,"Memory allocation failed"); if (mng_info->ob[object_id]->frozen) png_error(ping,"Cannot overwrite frozen MNG object buffer"); } else { if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image=DestroyImage (mng_info->ob[object_id]->image); mng_info->ob[object_id]->image=CloneImage(image,0,0,MagickTrue, &image->exception); if (mng_info->ob[object_id]->image != (Image *) NULL) mng_info->ob[object_id]->image->file=(FILE *) NULL; else png_error(ping, "Cloning image for object buffer failed"); if (ping_width > 250000L || ping_height > 250000L) png_error(ping,"PNG Image dimensions are too large."); mng_info->ob[object_id]->width=ping_width; mng_info->ob[object_id]->height=ping_height; mng_info->ob[object_id]->color_type=ping_color_type; mng_info->ob[object_id]->sample_depth=ping_bit_depth; mng_info->ob[object_id]->interlace_method=ping_interlace_method; mng_info->ob[object_id]->compression_method= ping_compression_method; mng_info->ob[object_id]->filter_method=ping_filter_method; if (png_get_valid(ping,ping_info,PNG_INFO_PLTE)) { png_colorp plte; /* Copy the PLTE to the object buffer. */ png_get_PLTE(ping,ping_info,&plte,&number_colors); mng_info->ob[object_id]->plte_length=number_colors; for (i=0; i < number_colors; i++) { mng_info->ob[object_id]->plte[i]=plte[i]; } } else mng_info->ob[object_id]->plte_length=0; } } #endif /* Set image->matte to MagickTrue if the input colortype supports * alpha or if a valid tRNS chunk is present, no matter whether there * is actual transparency present. */ image->matte=(((int) ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) || ((int) ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) || (png_get_valid(ping,ping_info,PNG_INFO_tRNS))) ? MagickTrue : MagickFalse; #if 0 /* I'm not sure what's wrong here but it does not work. */ if (image->matte != MagickFalse) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) (void) SetImageType(image,GrayscaleMatteType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteMatteType); else (void) SetImageType(image,TrueColorMatteType); } else { if (ping_color_type == PNG_COLOR_TYPE_GRAY) (void) SetImageType(image,GrayscaleType); else if (ping_color_type == PNG_COLOR_TYPE_PALETTE) (void) SetImageType(image,PaletteType); else (void) SetImageType(image,TrueColorType); } #endif /* Set more properties for identify to retrieve */ { char msg[MaxTextExtent]; if (num_text_total != 0) { /* libpng doesn't tell us whether they were tEXt, zTXt, or iTXt */ (void) FormatLocaleString(msg,MaxTextExtent, "%d tEXt/zTXt/iTXt chunks were found", num_text_total); (void) SetImageProperty(image,"png:text",msg); } if (num_raw_profiles != 0) { (void) FormatLocaleString(msg,MaxTextExtent, "%d were found", num_raw_profiles); (void) SetImageProperty(image,"png:text-encoded profiles",msg); } /* cHRM chunk: */ if (ping_found_cHRM != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Chromaticity, above)"); (void) SetImageProperty(image,"png:cHRM",msg); } /* bKGD chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_bKGD)) { (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found (see Background color, above)"); (void) SetImageProperty(image,"png:bKGD",msg); } (void) FormatLocaleString(msg,MaxTextExtent,"%s", "chunk was found"); /* iCCP chunk: */ if (ping_found_iCCP != MagickFalse) (void) SetImageProperty(image,"png:iCCP",msg); if (png_get_valid(ping,ping_info,PNG_INFO_tRNS)) (void) SetImageProperty(image,"png:tRNS",msg); #if defined(PNG_sRGB_SUPPORTED) /* sRGB chunk: */ if (ping_found_sRGB != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "intent=%d (%s)", (int) intent, Magick_RenderingIntentString_from_PNG_RenderingIntent(intent)); (void) SetImageProperty(image,"png:sRGB",msg); } #endif /* gAMA chunk: */ if (ping_found_gAMA != MagickFalse) { (void) FormatLocaleString(msg,MaxTextExtent, "gamma=%.8g (See Gamma, above)", file_gamma); (void) SetImageProperty(image,"png:gAMA",msg); } #if defined(PNG_pHYs_SUPPORTED) /* pHYs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_pHYs)) { (void) FormatLocaleString(msg,MaxTextExtent, "x_res=%.10g, y_res=%.10g, units=%d", (double) x_resolution,(double) y_resolution, unit_type); (void) SetImageProperty(image,"png:pHYs",msg); } #endif #if defined(PNG_oFFs_SUPPORTED) /* oFFs chunk: */ if (png_get_valid(ping,ping_info,PNG_INFO_oFFs)) { (void) FormatLocaleString(msg,MaxTextExtent,"x_off=%.20g, y_off=%.20g", (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:oFFs",msg); } #endif #if defined(PNG_tIME_SUPPORTED) read_tIME_chunk(image,ping,end_info); #endif /* caNv chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || (image->page.x != 0 || image->page.y != 0)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g, x_offset=%.20g, y_offset=%.20g", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); (void) SetImageProperty(image,"png:caNv",msg); } /* vpAg chunk: */ if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { (void) FormatLocaleString(msg,MaxTextExtent, "width=%.20g, height=%.20g", (double) image->page.width,(double) image->page.height); (void) SetImageProperty(image,"png:vpAg",msg); } } /* Relinquish resources. */ png_destroy_read_struct(&ping,&ping_info,&end_info); pixel_info=RelinquishVirtualMemory(pixel_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block, revert to * Throwing an Exception when an error occurs. */ return(image); /* end of reading one PNG image */ } static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* 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); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a PNG datastream. */ if (GetBlobSize(image) < 61) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } #if defined(JNG_SUPPORTED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d O n e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadOneJNGImage() reads a JPEG Network Graphics (JNG) image file % (minus the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadOneJNGImage method is: % % Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o mng_info: Specifies a pointer to a MngInfo structure. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { if (color_image != (Image *) NULL) color_image=DestroyImage(color_image); if (color_image_info != (ImageInfo *) NULL) color_image_info=DestroyImageInfo(color_image_info); ThrowReaderException(CorruptImageError,"CorruptImage"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJNGImage() reads a JPEG Network Graphics (JNG) image file % (including the 8-byte signature) and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the ReadJNGImage method is: % % Image *ReadJNGImage(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 *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; size_t count; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (LocaleCompare(image_info->magick,"JNG") != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify JNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Verify that file size large enough to contain a JNG datastream. */ if (GetBlobSize(image) < 147) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneJNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (image->columns == 0 || image->rows == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); ThrowReaderException(CorruptImageError,"CorruptImage"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()"); return(image); } #endif static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream", "`%s'", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, "object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters ", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage();"); return(image); } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadMNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOneMNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadMNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadMNGImage()"); return(GetFirstImageInList(image)); } #else /* PNG_LIBPNG_VER > 10011 */ static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "PNG library is too old","`%s'",image_info->filename); return(Image *) NULL; } static Image *ReadMNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { return(ReadPNGImage(image_info,exception)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNGImage() adds properties for the PNG 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 RegisterPNGImage method is: % % size_t RegisterPNGImage(void) % */ ModuleExport size_t RegisterPNGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MaxTextExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MaxTextExtent); } #endif entry=SetMagickInfo("MNG"); entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; entry->description=ConstantString("Multiple-image Network Graphics"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("Portable Network Graphics"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG8"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "8-bit indexed with optional binary transparency"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG24"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MaxTextExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,zlib_version,MaxTextExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 24-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG32"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 32-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG48"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 48-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG64"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 64-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG00"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString( "PNG inheriting bit-depth, color-type from original if possible"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JNG"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->description=ConstantString("JPEG Network Graphics"); entry->mime_type=ConstantString("image/x-jng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AllocateSemaphoreInfo(); #endif return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNGImage() removes format registrations made by the % PNG module from the list of supported formats. % % The format of the UnregisterPNGImage method is: % % UnregisterPNGImage(void) % */ ModuleExport void UnregisterPNGImage(void) { (void) UnregisterMagickInfo("MNG"); (void) UnregisterMagickInfo("PNG"); (void) UnregisterMagickInfo("PNG8"); (void) UnregisterMagickInfo("PNG24"); (void) UnregisterMagickInfo("PNG32"); (void) UnregisterMagickInfo("PNG48"); (void) UnregisterMagickInfo("PNG64"); (void) UnregisterMagickInfo("PNG00"); (void) UnregisterMagickInfo("JNG"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE if (ping_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&ping_semaphore); #endif } #if defined(MAGICKCORE_PNG_DELEGATE) #if PNG_LIBPNG_VER > 10011 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMNGImage() writes an image in the Portable Network Graphics % Group's "Multiple-image Network Graphics" encoded image format. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteMNGImage method is: % % MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % % To do (as of version 5.5.2, November 26, 2002 -- glennrp -- see also % "To do" under ReadPNGImage): % % Preserve all unknown and not-yet-handled known chunks found in input % PNG file and copy them into output PNG files according to the PNG % copying rules. % % Write the iCCP chunk at MNG level when (icc profile length > 0) % % Improve selection of color type (use indexed-colour or indexed-colour % with tRNS when 256 or fewer unique RGBA values are present). % % Figure out what to do with "dispose=<restore-to-previous>" (dispose == 3) % This will be complicated if we limit ourselves to generating MNG-LC % files. For now we ignore disposal method 3 and simply overlay the next % image on it. % % Check for identical PLTE's or PLTE/tRNS combinations and use a % global MNG PLTE or PLTE/tRNS combination when appropriate. % [mostly done 15 June 1999 but still need to take care of tRNS] % % Check for identical sRGB and replace with a global sRGB (and remove % gAMA/cHRM if sRGB is found; check for identical gAMA/cHRM and % replace with global gAMA/cHRM (or with sRGB if appropriate; replace % local gAMA/cHRM with local sRGB if appropriate). % % Check for identical sBIT chunks and write global ones. % % Provide option to skip writing the signature tEXt chunks. % % Use signatures to detect identical objects and reuse the first % instance of such objects instead of writing duplicate objects. % % Use a smaller-than-32k value of compression window size when % appropriate. % % Encode JNG datastreams. Mostly done as of 5.5.2; need to write % ancillary text chunks and save profiles. % % Provide an option to force LC files (to ensure exact framing rate) % instead of VLC. % % Provide an option to force VLC files instead of LC, even when offsets % are present. This will involve expanding the embedded images with a % transparent region at the top and/or left. */ static void Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping,(png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MaxTextExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } static MagickBooleanType Magick_png_write_chunk_from_profile(Image *image, const char *string, MagickBooleanType logging) { char *name; const StringInfo *profile; unsigned char *data; png_uint_32 length; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (const StringInfo *) NULL) { StringInfo *ping_profile; if (LocaleNCompare(name,string,11) == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Found %s profile",name); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); data[4]=data[3]; data[3]=data[2]; data[2]=data[1]; data[1]=data[0]; (void) WriteBlobMSBULong(image,length-5); /* data length */ (void) WriteBlob(image,length-1,data+1); (void) WriteBlobMSBULong(image,crc32(0,data+1,(uInt) length-1)); ping_profile=DestroyStringInfo(ping_profile); } } name=GetNextImageProfile(image); } return(MagickTrue); } #if defined(PNG_tIME_SUPPORTED) static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, const char *date) { unsigned int day, hour, minute, month, second, year; png_time ptime; time_t ttime; if (date != (const char *) NULL) { if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute, &second) != 6) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError, "Invalid date format specified for png:tIME","`%s'", image->filename); return; } ptime.year=(png_uint_16) year; ptime.month=(png_byte) month; ptime.day=(png_byte) day; ptime.hour=(png_byte) hour; ptime.minute=(png_byte) minute; ptime.second=(png_byte) second; } else { time(&ttime); png_convert_from_time_t(&ptime,ttime); } png_set_tIME(ping,info,&ptime); } #endif /* Write one PNG image */ static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { char s[2]; char im_vers[32], libpng_runv[32], libpng_vers[32], zlib_runv[32], zlib_vers[32]; const char *name, *property, *value; const StringInfo *profile; int num_passes, pass, ping_wrote_caNv; png_byte ping_trans_alpha[256]; png_color palette[257]; png_color_16 ping_background, ping_trans_color; png_info *ping_info; png_struct *ping; png_uint_32 ping_height, ping_width; ssize_t y; MagickBooleanType image_matte, logging, matte, ping_have_blob, ping_have_cheap_transparency, ping_have_color, ping_have_non_bw, ping_have_PLTE, ping_have_bKGD, ping_have_eXIf, ping_have_iCCP, ping_have_pHYs, ping_have_sRGB, ping_have_tRNS, ping_exclude_bKGD, ping_exclude_cHRM, ping_exclude_date, /* ping_exclude_EXIF, */ ping_exclude_eXIf, ping_exclude_gAMA, ping_exclude_iCCP, /* ping_exclude_iTXt, */ ping_exclude_oFFs, ping_exclude_pHYs, ping_exclude_sRGB, ping_exclude_tEXt, ping_exclude_tIME, /* ping_exclude_tRNS, */ ping_exclude_vpAg, ping_exclude_caNv, ping_exclude_zCCP, /* hex-encoded iCCP */ ping_exclude_zTXt, ping_preserve_colormap, ping_preserve_iCCP, ping_need_colortype_warning, status, tried_332, tried_333, tried_444; MemoryInfo *volatile pixel_info; QuantumInfo *quantum_info; register ssize_t i, x; unsigned char *ping_pixels; volatile int image_colors, ping_bit_depth, ping_color_type, ping_interlace_method, ping_compression_method, ping_filter_method, ping_num_trans; volatile size_t image_depth, old_bit_depth; size_t quality, rowbytes, save_image_depth; int j, number_colors, number_opaque, number_semitransparent, number_transparent, ping_pHYs_unit_type; png_uint_32 ping_pHYs_x_resolution, ping_pHYs_y_resolution; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOnePNGImage()"); /* Define these outside of the following "if logging()" block so they will * show in debuggers. */ *im_vers='\0'; (void) ConcatenateMagickString(im_vers, MagickLibVersionText,MaxTextExtent); (void) ConcatenateMagickString(im_vers, MagickLibAddendum,MaxTextExtent); *libpng_vers='\0'; (void) ConcatenateMagickString(libpng_vers, PNG_LIBPNG_VER_STRING,32); *libpng_runv='\0'; (void) ConcatenateMagickString(libpng_runv, png_get_libpng_ver(NULL),32); *zlib_vers='\0'; (void) ConcatenateMagickString(zlib_vers, ZLIB_VERSION,32); *zlib_runv='\0'; (void) ConcatenateMagickString(zlib_runv, zlib_version,32); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s", im_vers); (void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s", libpng_vers); if (LocaleCompare(libpng_vers,libpng_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", libpng_runv); } (void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s", zlib_vers); if (LocaleCompare(zlib_vers,zlib_runv) != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s", zlib_runv); } } /* Initialize some stuff */ ping_bit_depth=0, ping_color_type=0, ping_interlace_method=0, ping_compression_method=0, ping_filter_method=0, ping_num_trans = 0; ping_background.red = 0; ping_background.green = 0; ping_background.blue = 0; ping_background.gray = 0; ping_background.index = 0; ping_trans_color.red=0; ping_trans_color.green=0; ping_trans_color.blue=0; ping_trans_color.gray=0; ping_pHYs_unit_type = 0; ping_pHYs_x_resolution = 0; ping_pHYs_y_resolution = 0; ping_have_blob=MagickFalse; ping_have_cheap_transparency=MagickFalse; ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; ping_have_PLTE=MagickFalse; ping_have_bKGD=MagickFalse; ping_have_eXIf=MagickTrue; ping_have_iCCP=MagickFalse; ping_have_pHYs=MagickFalse; ping_have_sRGB=MagickFalse; ping_have_tRNS=MagickFalse; ping_exclude_bKGD=mng_info->ping_exclude_bKGD; ping_exclude_caNv=mng_info->ping_exclude_caNv; ping_exclude_cHRM=mng_info->ping_exclude_cHRM; ping_exclude_date=mng_info->ping_exclude_date; /* ping_exclude_EXIF=mng_info->ping_exclude_EXIF; */ ping_exclude_eXIf=mng_info->ping_exclude_eXIf; ping_exclude_gAMA=mng_info->ping_exclude_gAMA; ping_exclude_iCCP=mng_info->ping_exclude_iCCP; /* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */ ping_exclude_oFFs=mng_info->ping_exclude_oFFs; ping_exclude_pHYs=mng_info->ping_exclude_pHYs; ping_exclude_sRGB=mng_info->ping_exclude_sRGB; ping_exclude_tEXt=mng_info->ping_exclude_tEXt; ping_exclude_tIME=mng_info->ping_exclude_tIME; /* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */ ping_exclude_vpAg=mng_info->ping_exclude_vpAg; ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */ ping_exclude_zTXt=mng_info->ping_exclude_zTXt; ping_preserve_colormap = mng_info->ping_preserve_colormap; ping_preserve_iCCP = mng_info->ping_preserve_iCCP; ping_need_colortype_warning = MagickFalse; property=(const char *) NULL; /* Recognize the ICC sRGB profile and convert it to the sRGB chunk, * i.e., eliminate the ICC profile and set image->rendering_intent. * Note that this will not involve any changes to the actual pixels * but merely passes information to applications that read the resulting * PNG image. * * To do: recognize other variants of the sRGB profile, using the CRC to * verify all recognized variants including the 7 already known. * * Work around libpng16+ rejecting some "known invalid sRGB profiles". * * Use something other than image->rendering_intent to record the fact * that the sRGB profile was found. * * Record the ICC version (currently v2 or v4) of the incoming sRGB ICC * profile. Record the Blackpoint Compensation, if any. */ if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse) { char *name; const StringInfo *profile; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { int icheck, got_crc=0; png_uint_32 length, profile_crc=0; unsigned char *data; length=(png_uint_32) GetStringInfoLength(profile); for (icheck=0; sRGB_info[icheck].len > 0; icheck++) { if (length == sRGB_info[icheck].len) { if (got_crc == 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile (potentially sRGB)", (unsigned long) length); data=GetStringInfoDatum(profile); profile_crc=crc32(0,data,length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " with crc=%8x",(unsigned int) profile_crc); got_crc++; } if (profile_crc == sRGB_info[icheck].crc) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " It is sRGB with rendering intent = %s", Magick_RenderingIntentString_from_PNG_RenderingIntent( sRGB_info[icheck].intent)); if (image->rendering_intent==UndefinedIntent) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent( sRGB_info[icheck].intent); } ping_exclude_iCCP = MagickTrue; ping_exclude_zCCP = MagickTrue; ping_have_sRGB = MagickTrue; break; } } } if (sRGB_info[icheck].len == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Got a %lu-byte ICC profile not recognized as sRGB", (unsigned long) length); } } name=GetNextImageProfile(image); } } number_opaque = 0; number_semitransparent = 0; number_transparent = 0; if (logging != MagickFalse) { if (image->storage_class == UndefinedClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=UndefinedClass"); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=DirectClass"); if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->storage_class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->magick= %s",image_info->magick); (void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ? " image->taint=MagickTrue": " image->taint=MagickFalse"); } if (image->storage_class == PseudoClass && (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (mng_info->write_png_colortype != 1 && mng_info->write_png_colortype != 5))) { (void) SyncImage(image); image->storage_class = DirectClass; } if (ping_preserve_colormap == MagickFalse) { if (image->storage_class != PseudoClass && image->colormap != NULL) { /* Free the bogus colormap; it can cause trouble later */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Freeing bogus colormap"); (void) RelinquishMagickMemory(image->colormap); image->colormap=NULL; } } if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Sometimes we get PseudoClass images whose RGB values don't match the colors in the colormap. This code syncs the RGB values. */ if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass) (void) SyncImage(image); #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (image->depth > 8) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reducing PNG bit depth to 8 since this is a Q8 build."); image->depth=8; } #endif /* Respect the -depth option */ if (image->depth < 4) { register PixelPacket *r; ExceptionInfo *exception; exception=(&image->exception); if (image->depth > 2) { /* Scale to 4-bit */ LBR04PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR04PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR04PacketRGBO(image->colormap[i]); } } } else if (image->depth > 1) { /* Scale to 2-bit */ LBR02PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR02PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR02PacketRGBO(image->colormap[i]); } } } else { /* Scale to 1-bit */ LBR01PacketRGBO(image->background_color); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { LBR01PixelRGBO(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->storage_class == PseudoClass && image->colormap != NULL) { for (i=0; i < (ssize_t) image->colors; i++) { LBR01PacketRGBO(image->colormap[i]); } } } } /* To do: set to next higher multiple of 8 */ if (image->depth < 8) image->depth=8; #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy */ if (image->depth > 8) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (image->depth == 16 && mng_info->write_png_depth != 16) if (mng_info->write_png8 || LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif image_colors = (int) image->colors; if (mng_info->write_png_colortype && (mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 && mng_info->write_png_colortype < 4 && image->matte == MagickFalse))) { /* Avoid the expensive BUILD_PALETTE operation if we're sure that we * are not going to need the result. */ number_opaque = (int) image->colors; if (mng_info->write_png_colortype == 1 || mng_info->write_png_colortype == 5) ping_have_color=MagickFalse; else ping_have_color=MagickTrue; ping_have_non_bw=MagickFalse; if (image->matte != MagickFalse) { number_transparent = 2; number_semitransparent = 1; } else { number_transparent = 0; number_semitransparent = 0; } } if (mng_info->write_png_colortype < 7) { /* BUILD_PALETTE * * Normally we run this just once, but in the case of writing PNG8 * we reduce the transparency to binary and run again, then if there * are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1 * RGBA palette and run again, and then to a simple 3-3-2-1 RGBA * palette. Then (To do) we take care of a final reduction that is only * needed if there are still 256 colors present and one of them has both * transparent and opaque instances. */ tried_332 = MagickFalse; tried_333 = MagickFalse; tried_444 = MagickFalse; for (j=0; j<6; j++) { /* * Sometimes we get DirectClass images that have 256 colors or fewer. * This code will build a colormap. * * Also, sometimes we get PseudoClass images with an out-of-date * colormap. This code will replace the colormap with a new one. * Sometimes we get PseudoClass images that have more than 256 colors. * This code will delete the colormap and change the image to * DirectClass. * * If image->matte is MagickFalse, we ignore the opacity channel * even though it sometimes contains left-over non-opaque values. * * Also we gather some information (number of opaque, transparent, * and semitransparent pixels, and whether the image has any non-gray * pixels or only black-and-white pixels) that we might need later. * * Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6) * we need to check for bogus non-opaque values, at least. */ ExceptionInfo *exception; int n; PixelPacket opaque[260], semitransparent[260], transparent[260]; register IndexPacket *indexes; register const PixelPacket *s, *q; register PixelPacket *r; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Enter BUILD_PALETTE:"); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->columns=%.20g",(double) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->rows=%.20g",(double) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); if (image->storage_class == PseudoClass && image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Original colormap:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < 256; i++) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } for (i=image->colors - 10; i < (ssize_t) image->colors; i++) { if (i > 255) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d",(int) image->colors); if (image->colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " (zero means unknown)"); if (ping_preserve_colormap == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Regenerate the colormap"); } exception=(&image->exception); image_colors=0; number_opaque = 0; number_semitransparent = 0; number_transparent = 0; for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte == MagickFalse || GetPixelOpacity(q) == OpaqueOpacity) { if (number_opaque < 259) { if (number_opaque == 0) { GetPixelRGB(q, opaque); opaque[0].opacity=OpaqueOpacity; number_opaque=1; } for (i=0; i< (ssize_t) number_opaque; i++) { if (IsColorEqual(q, opaque+i)) break; } if (i == (ssize_t) number_opaque && number_opaque < 259) { number_opaque++; GetPixelRGB(q, opaque+i); opaque[i].opacity=OpaqueOpacity; } } } else if (q->opacity == TransparentOpacity) { if (number_transparent < 259) { if (number_transparent == 0) { GetPixelRGBO(q, transparent); ping_trans_color.red= (unsigned short) GetPixelRed(q); ping_trans_color.green= (unsigned short) GetPixelGreen(q); ping_trans_color.blue= (unsigned short) GetPixelBlue(q); ping_trans_color.gray= (unsigned short) GetPixelRed(q); number_transparent = 1; } for (i=0; i< (ssize_t) number_transparent; i++) { if (IsColorEqual(q, transparent+i)) break; } if (i == (ssize_t) number_transparent && number_transparent < 259) { number_transparent++; GetPixelRGBO(q, transparent+i); } } } else { if (number_semitransparent < 259) { if (number_semitransparent == 0) { GetPixelRGBO(q, semitransparent); number_semitransparent = 1; } for (i=0; i< (ssize_t) number_semitransparent; i++) { if (IsColorEqual(q, semitransparent+i) && GetPixelOpacity(q) == semitransparent[i].opacity) break; } if (i == (ssize_t) number_semitransparent && number_semitransparent < 259) { number_semitransparent++; GetPixelRGBO(q, semitransparent+i); } } } q++; } } if (mng_info->write_png8 == MagickFalse && ping_exclude_bKGD == MagickFalse) { /* Add the background color to the palette, if it * isn't already there. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Check colormap for background (%d,%d,%d)", (int) image->background_color.red, (int) image->background_color.green, (int) image->background_color.blue); } for (i=0; i<number_opaque; i++) { if (opaque[i].red == image->background_color.red && opaque[i].green == image->background_color.green && opaque[i].blue == image->background_color.blue) break; } if (number_opaque < 259 && i == number_opaque) { opaque[i] = image->background_color; ping_background.index = i; number_opaque++; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d",(int) i); } } else if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in the colormap to add background color"); } image_colors=number_opaque+number_transparent+number_semitransparent; if (logging != MagickFalse) { if (image_colors > 256) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has more than 256 colors"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has %d colors",image_colors); } if (ping_preserve_colormap != MagickFalse) break; if (mng_info->write_png_colortype != 7) /* We won't need this info */ { ping_have_color=MagickFalse; ping_have_non_bw=MagickFalse; if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "incompatible colorspace"); ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; } if(image_colors > 256) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != GetPixelGreen(s) || GetPixelRed(s) != GetPixelBlue(s)) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } s++; } if (ping_have_color != MagickFalse) break; /* Worst case is black-and-white; we are looking at every * pixel twice. */ if (ping_have_non_bw == MagickFalse) { s=q; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelRed(s) != 0 && GetPixelRed(s) != QuantumRange) { ping_have_non_bw=MagickTrue; break; } s++; } } } } } if (image_colors < 257) { PixelPacket colormap[260]; /* * Initialize image colormap. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Sort the new colormap"); /* Sort palette, transparent first */; n = 0; for (i=0; i<number_transparent; i++) colormap[n++] = transparent[i]; for (i=0; i<number_semitransparent; i++) colormap[n++] = semitransparent[i]; for (i=0; i<number_opaque; i++) colormap[n++] = opaque[i]; ping_background.index += (number_transparent + number_semitransparent); /* image_colors < 257; search the colormap instead of the pixels * to get ping_have_color and ping_have_non_bw */ for (i=0; i<n; i++) { if (ping_have_color == MagickFalse) { if (colormap[i].red != colormap[i].green || colormap[i].red != colormap[i].blue) { ping_have_color=MagickTrue; ping_have_non_bw=MagickTrue; break; } } if (ping_have_non_bw == MagickFalse) { if (colormap[i].red != 0 && colormap[i].red != QuantumRange) ping_have_non_bw=MagickTrue; } } if ((mng_info->ping_exclude_tRNS == MagickFalse || (number_transparent == 0 && number_semitransparent == 0)) && (((mng_info->write_png_colortype-1) == PNG_COLOR_TYPE_PALETTE) || (mng_info->write_png_colortype == 0))) { if (logging != MagickFalse) { if (n != (ssize_t) image_colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_colors (%d) and n (%d) don't match", image_colors, n); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireImageColormap"); } image->colors = image_colors; if (AcquireImageColormap(image,image_colors) == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); for (i=0; i< (ssize_t) image_colors; i++) image->colormap[i] = colormap[i]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d (%d)", (int) image->colors, image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Update the pixel indexes"); } /* Sync the pixel indices with the new colormap */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i< (ssize_t) image_colors; i++) { if ((image->matte == MagickFalse || image->colormap[i].opacity == GetPixelOpacity(q)) && image->colormap[i].red == GetPixelRed(q) && image->colormap[i].green == GetPixelGreen(q) && image->colormap[i].blue == GetPixelBlue(q)) { SetPixelIndex(indexes+x,i); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->colors=%d", (int) image->colors); if (image->colormap != NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " i (red,green,blue,opacity)"); for (i=0; i < (ssize_t) image->colors; i++) { if (i < 300 || i >= (ssize_t) image->colors - 10) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %d (%d,%d,%d,%d)", (int) i, (int) image->colormap[i].red, (int) image->colormap[i].green, (int) image->colormap[i].blue, (int) image->colormap[i].opacity); } } } if (number_transparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent = %d", number_transparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_transparent > 256"); if (number_opaque < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque = %d", number_opaque); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_opaque > 256"); if (number_semitransparent < 257) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent = %d", number_semitransparent); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " number_semitransparent > 256"); if (ping_have_non_bw == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are black or white"); else if (ping_have_color == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " All pixels and the background are gray"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " At least one pixel or the background is non-gray"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Exit BUILD_PALETTE:"); } if (mng_info->write_png8 == MagickFalse) break; /* Make any reductions necessary for the PNG8 format */ if (image_colors <= 256 && image_colors != 0 && image->colormap != NULL && number_semitransparent == 0 && number_transparent <= 1) break; /* PNG8 can't have semitransparent colors so we threshold the * opacity to 0 or OpaqueOpacity, and PNG8 can only have one * transparent color so if more than one is transparent we merge * them into image->background_color. */ if (number_semitransparent != 0 || number_transparent > 1) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Thresholding the alpha channel to binary"); for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) > TransparentOpacity/2) { SetPixelOpacity(r,TransparentOpacity); SetPixelRgb(r,&image->background_color); } else SetPixelOpacity(r,OpaqueOpacity); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image_colors != 0 && image_colors <= 256 && image->colormap != NULL) for (i=0; i<image_colors; i++) image->colormap[i].opacity = (image->colormap[i].opacity > TransparentOpacity/2 ? TransparentOpacity : OpaqueOpacity); } continue; } /* PNG8 can't have more than 256 colors so we quantize the pixels and * background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the * image is mostly gray, the 4-4-4-1 palette is likely to end up with 256 * colors or less. */ if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 4-4-4"); tried_444 = MagickTrue; LBR04PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 4-4-4"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR04PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 4-4-4"); for (i=0; i<image_colors; i++) { LBR04PacketRGB(image->colormap[i]); } } continue; } if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-3"); tried_333 = MagickTrue; LBR03PacketRGB(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-3-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR03PixelRGB(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-3-1"); for (i=0; i<image_colors; i++) { LBR03PacketRGB(image->colormap[i]); } } continue; } if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the background color to 3-3-2"); tried_332 = MagickTrue; /* Red and green were already done so we only quantize the blue * channel */ LBR02PacketBlue(image->background_color); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(r) == OpaqueOpacity) LBR02PixelBlue(r); r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else /* Should not reach this; colormap already exists and must be <= 256 */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Quantizing the colormap to 3-3-2-1"); for (i=0; i<image_colors; i++) { LBR02PacketBlue(image->colormap[i]); } } continue; } if (image_colors == 0 || image_colors > 256) { /* Take care of special case with 256 opaque colors + 1 transparent * color. We don't need to quantize to 2-3-2-1; we only need to * eliminate one color, so we'll merge the two darkest red * colors (0x49, 0, 0) -> (0x24, 0, 0). */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red background colors to 3-3-2-1"); if (ScaleQuantumToChar(image->background_color.red) == 0x49 && ScaleQuantumToChar(image->background_color.green) == 0x00 && ScaleQuantumToChar(image->background_color.blue) == 0x00) { image->background_color.red=ScaleCharToQuantum(0x24); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Merging two dark red pixel colors to 3-3-2-1"); if (image->colormap == NULL) { for (y=0; y < (ssize_t) image->rows; y++) { r=GetAuthenticPixels(image,0,y,image->columns,1, exception); if (r == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (ScaleQuantumToChar(GetPixelRed(r)) == 0x49 && ScaleQuantumToChar(GetPixelGreen(r)) == 0x00 && ScaleQuantumToChar(GetPixelBlue(r)) == 0x00 && GetPixelOpacity(r) == OpaqueOpacity) { SetPixelRed(r,ScaleCharToQuantum(0x24)); } r++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } else { for (i=0; i<image_colors; i++) { if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 && ScaleQuantumToChar(image->colormap[i].green) == 0x00 && ScaleQuantumToChar(image->colormap[i].blue) == 0x00) { image->colormap[i].red=ScaleCharToQuantum(0x24); } } } } } } /* END OF BUILD_PALETTE */ /* If we are excluding the tRNS chunk and there is transparency, * then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6) * PNG. */ if (mng_info->ping_exclude_tRNS != MagickFalse && (number_transparent != 0 || number_semitransparent != 0)) { unsigned int colortype=mng_info->write_png_colortype; if (ping_have_color == MagickFalse) mng_info->write_png_colortype = 5; else mng_info->write_png_colortype = 7; if (colortype != 0 && mng_info->write_png_colortype != colortype) ping_need_colortype_warning=MagickTrue; } /* See if cheap transparency is possible. It is only possible * when there is a single transparent color, no semitransparent * color, and no opaque color that has the same RGB components * as the transparent color. We only need this information if * we are writing a PNG with colortype 0 or 2, and we have not * excluded the tRNS chunk. */ if (number_transparent == 1 && mng_info->write_png_colortype < 4) { ping_have_cheap_transparency = MagickTrue; if (number_semitransparent != 0) ping_have_cheap_transparency = MagickFalse; else if (image_colors == 0 || image_colors > 256 || image->colormap == NULL) { ExceptionInfo *exception; register const PixelPacket *q; exception=(&image->exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (q->opacity != TransparentOpacity && (unsigned short) GetPixelRed(q) == ping_trans_color.red && (unsigned short) GetPixelGreen(q) == ping_trans_color.green && (unsigned short) GetPixelBlue(q) == ping_trans_color.blue) { ping_have_cheap_transparency = MagickFalse; break; } q++; } if (ping_have_cheap_transparency == MagickFalse) break; } } else { /* Assuming that image->colormap[0] is the one transparent color * and that all others are opaque. */ if (image_colors > 1) for (i=1; i<image_colors; i++) if (image->colormap[i].red == image->colormap[0].red && image->colormap[i].green == image->colormap[0].green && image->colormap[i].blue == image->colormap[0].blue) { ping_have_cheap_transparency = MagickFalse; break; } } if (logging != MagickFalse) { if (ping_have_cheap_transparency == MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is not possible."); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Cheap transparency is possible."); } } else ping_have_cheap_transparency = MagickFalse; image_depth=image->depth; quantum_info = (QuantumInfo *) NULL; number_colors=0; image_colors=(int) image->colors; image_matte=image->matte; if (mng_info->write_png_colortype < 5) mng_info->IsPalette=image->storage_class == PseudoClass && image_colors <= 256 && image->colormap != NULL; else mng_info->IsPalette = MagickFalse; if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) && (image->colors == 0 || image->colormap == NULL)) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, "Cannot write PNG8 or color-type 3; colormap is NULL", "`%s'",image->filename); return(MagickFalse); } /* Allocate the PNG structures */ #ifdef PNG_USER_MEM_SUPPORTED ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL, (png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free); #else ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,image, MagickPNGErrorHandler,MagickPNGWarningHandler); #endif if (ping == (png_struct *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); ping_info=png_create_info_struct(ping); if (ping_info == (png_info *) NULL) { png_destroy_write_struct(&ping,(png_info **) NULL); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } png_set_write_fn(ping,image,png_put_data,png_flush_data); pixel_info=(MemoryInfo *) NULL; if (setjmp(png_jmpbuf(ping))) { /* PNG write failed. */ #ifdef PNG_DEBUG if (image_info->verbose) (void) printf("PNG write has failed.\n"); #endif png_destroy_write_struct(&ping,&ping_info); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); return(MagickFalse); } /* { For navigation to end of SETJMP-protected block. Within this * block, use png_error() instead of Throwing an Exception, to ensure * that libpng is able to clean up, and that the semaphore is unlocked. */ #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE LockSemaphoreInfo(ping_semaphore); #endif #ifdef PNG_BENIGN_ERRORS_SUPPORTED /* Allow benign errors */ png_set_benign_errors(ping, 1); #endif #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Reject images with too many rows or columns */ png_set_user_limits(ping, (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(WidthResource)), (png_uint_32) MagickMin(0x7fffffffL, GetMagickResourceLimit(HeightResource))); #endif /* PNG_SET_USER_LIMITS_SUPPORTED */ /* Prepare PNG for writing. */ #if defined(PNG_MNG_FEATURES_SUPPORTED) if (mng_info->write_mng) { (void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES); # ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Disable new libpng-1.5.10 feature when writing a MNG because * zero-length PLTE is OK */ png_set_check_for_invalid_index (ping, 0); # endif } #else # ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if (mng_info->write_mng) png_permit_empty_plte(ping,MagickTrue); # endif #endif x=0; ping_width=(png_uint_32) image->columns; ping_height=(png_uint_32) image->rows; if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32) image_depth=8; if (mng_info->write_png48 || mng_info->write_png64) image_depth=16; if (mng_info->write_png_depth != 0) image_depth=mng_info->write_png_depth; /* Adjust requested depth to next higher valid depth if necessary */ if (image_depth > 8) image_depth=16; if ((image_depth > 4) && (image_depth < 8)) image_depth=8; if (image_depth == 3) image_depth=4; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width=%.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height=%.20g",(double) ping_height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_matte=%.20g",(double) image->matte); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth=%.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative ping_bit_depth=%.20g",(double) image_depth); } save_image_depth=image_depth; ping_bit_depth=(png_byte) save_image_depth; #if defined(PNG_pHYs_SUPPORTED) if (ping_exclude_pHYs == MagickFalse) { if ((image->x_resolution != 0) && (image->y_resolution != 0) && (!mng_info->write_mng || !mng_info->equal_physs)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); if (image->units == PixelsPerInchResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution= (png_uint_32) ((100.0*image->x_resolution+0.5)/2.54); ping_pHYs_y_resolution= (png_uint_32) ((100.0*image->y_resolution+0.5)/2.54); } else if (image->units == PixelsPerCentimeterResolution) { ping_pHYs_unit_type=PNG_RESOLUTION_METER; ping_pHYs_x_resolution=(png_uint_32) (100.0*image->x_resolution+0.5); ping_pHYs_y_resolution=(png_uint_32) (100.0*image->y_resolution+0.5); } else { ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN; ping_pHYs_x_resolution=(png_uint_32) image->x_resolution; ping_pHYs_y_resolution=(png_uint_32) image->y_resolution; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.", (double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution, (int) ping_pHYs_unit_type); ping_have_pHYs = MagickTrue; } } #endif if (ping_exclude_bKGD == MagickFalse) { if ((!mng_info->adjoin || !mng_info->equal_backgrounds)) { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_background.red=(png_uint_16) (ScaleQuantumToShort(image->background_color.red) & mask); ping_background.green=(png_uint_16) (ScaleQuantumToShort(image->background_color.green) & mask); ping_background.blue=(png_uint_16) (ScaleQuantumToShort(image->background_color.blue) & mask); ping_background.gray=(png_uint_16) ping_background.green; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (1)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth=%d",ping_bit_depth); } ping_have_bKGD = MagickTrue; } /* Select the color type. */ matte=image_matte; old_bit_depth=0; if (mng_info->IsPalette && mng_info->write_png8) { /* To do: make this a function cause it's used twice, except for reducing the sample depth from 8. */ number_colors=image_colors; ping_have_tRNS=MagickFalse; /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors (%d)", number_colors, image_colors); for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), #if MAGICKCORE_QUANTUM_DEPTH == 8 " %3ld (%3d,%3d,%3d)", #else " %5ld (%5d,%5d,%5d)", #endif (long) i,palette[i].red,palette[i].green,palette[i].blue); } ping_have_PLTE=MagickTrue; image_depth=ping_bit_depth; ping_num_trans=0; if (matte != MagickFalse) { /* Identify which colormap entry is transparent. */ assert(number_colors <= 256); assert(image->colormap != NULL); for (i=0; i < (ssize_t) number_transparent; i++) ping_trans_alpha[i]=0; ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else ping_have_tRNS=MagickTrue; } if (ping_exclude_bKGD == MagickFalse) { /* * Identify which colormap entry is the background color. */ for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++) if (IsPNGColorEqual(ping_background,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background_color index is %d", (int) ping_background.index); } } } /* end of write_png8 */ else if (mng_info->write_png_colortype == 1) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; } else if (mng_info->write_png24 || mng_info->write_png48 || mng_info->write_png_colortype == 3) { image_matte=MagickFalse; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; } else if (mng_info->write_png32 || mng_info->write_png64 || mng_info->write_png_colortype == 7) { image_matte=MagickTrue; ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; } else /* mng_info->write_pngNN not specified */ { image_depth=ping_bit_depth; if (mng_info->write_png_colortype != 0) { ping_color_type=(png_byte) mng_info->write_png_colortype-1; if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) image_matte=MagickTrue; else image_matte=MagickFalse; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG colortype %d was specified:",(int) ping_color_type); } else /* write_png_colortype not specified */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selecting PNG colortype:"); ping_color_type=(png_byte) ((matte != MagickFalse)? PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB); if (image_info->type == TrueColorType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } if (image_info->type == TrueColorMatteType) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA; image_matte=MagickTrue; } if (image_info->type == PaletteType || image_info->type == PaletteMatteType) ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (mng_info->write_png_colortype == 0 && image_info->type == UndefinedType) { if (ping_have_color == MagickFalse) { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA; image_matte=MagickTrue; } } else { if (image_matte == MagickFalse) { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB; image_matte=MagickFalse; } else { ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA; image_matte=MagickTrue; } } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Selected PNG colortype=%d",ping_color_type); if (ping_bit_depth < 8) { if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA || ping_color_type == PNG_COLOR_TYPE_RGB || ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA) ping_bit_depth=8; } old_bit_depth=ping_bit_depth; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->matte == MagickFalse && ping_have_non_bw == MagickFalse) ping_bit_depth=1; } if (ping_color_type == PNG_COLOR_TYPE_PALETTE) { size_t one = 1; ping_bit_depth=1; if (image->colors == 0) { /* DO SOMETHING */ png_error(ping,"image has 0 colors"); } while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) image_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG bit depth: %d",ping_bit_depth); } if (ping_bit_depth < (int) mng_info->write_png_depth) ping_bit_depth = mng_info->write_png_depth; } image_depth=ping_bit_depth; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Tentative PNG color type: %s (%.20g)", PngColorTypeToString(ping_color_type), (double) ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_info->type: %.20g",(double) image_info->type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image_depth: %.20g",(double) image_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->depth: %.20g",(double) image->depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_bit_depth: %.20g",(double) ping_bit_depth); } if (matte != MagickFalse) { if (mng_info->IsPalette) { if (mng_info->write_png_colortype == 0) { ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; if (ping_have_color != MagickFalse) ping_color_type=PNG_COLOR_TYPE_RGBA; } /* * Determine if there is any transparent color. */ if (number_transparent + number_semitransparent == 0) { /* No transparent pixels are present. Change 4 or 6 to 0 or 2. */ image_matte=MagickFalse; if (mng_info->write_png_colortype == 0) ping_color_type&=0x03; } else { unsigned int mask; mask=0xffff; if (ping_bit_depth == 8) mask=0x00ff; if (ping_bit_depth == 4) mask=0x000f; if (ping_bit_depth == 2) mask=0x0003; if (ping_bit_depth == 1) mask=0x0001; ping_trans_color.red=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].red) & mask); ping_trans_color.green=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].green) & mask); ping_trans_color.blue=(png_uint_16) (ScaleQuantumToShort(image->colormap[0].blue) & mask); ping_trans_color.gray=(png_uint_16) (ScaleQuantumToShort(ClampToQuantum(GetPixelLuma(image, image->colormap))) & mask); ping_trans_color.index=(png_byte) 0; ping_have_tRNS=MagickTrue; } if (ping_have_tRNS != MagickFalse) { /* * Determine if there is one and only one transparent color * and if so if it is fully transparent. */ if (ping_have_cheap_transparency == MagickFalse) ping_have_tRNS=MagickFalse; } if (ping_have_tRNS != MagickFalse) { if (mng_info->write_png_colortype == 0) ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */ if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } else { if (image_depth == 8) { ping_trans_color.red&=0xff; ping_trans_color.green&=0xff; ping_trans_color.blue&=0xff; ping_trans_color.gray&=0xff; } } } matte=image_matte; if (ping_have_tRNS != MagickFalse) image_matte=MagickFalse; if ((mng_info->IsPalette) && mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE && ping_have_color == MagickFalse && (image_matte == MagickFalse || image_depth >= 8)) { size_t one=1; if (image_matte != MagickFalse) ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA; else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA) { ping_color_type=PNG_COLOR_TYPE_GRAY; if (save_image_depth == 16 && image_depth == 8) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (0)"); } ping_trans_color.gray*=0x0101; } } if (image_depth > MAGICKCORE_QUANTUM_DEPTH) image_depth=MAGICKCORE_QUANTUM_DEPTH; if ((image_colors == 0) || ((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize)) image_colors=(int) (one << image_depth); if (image_depth > 8) ping_bit_depth=16; else { ping_bit_depth=8; if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { if(!mng_info->write_png_depth) { ping_bit_depth=1; while ((int) (one << ping_bit_depth) < (ssize_t) image_colors) ping_bit_depth <<= 1; } } else if (ping_color_type == PNG_COLOR_TYPE_GRAY && image_colors < 17 && mng_info->IsPalette) { /* Check if grayscale is reducible */ int depth_4_ok=MagickTrue, depth_2_ok=MagickTrue, depth_1_ok=MagickTrue; for (i=0; i < (ssize_t) image_colors; i++) { unsigned char intensity; intensity=ScaleQuantumToChar(image->colormap[i].red); if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4)) depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2)) depth_2_ok=depth_1_ok=MagickFalse; else if ((intensity & 0x01) != ((intensity & 0x02) >> 1)) depth_1_ok=MagickFalse; } if (depth_1_ok && mng_info->write_png_depth <= 1) ping_bit_depth=1; else if (depth_2_ok && mng_info->write_png_depth <= 2) ping_bit_depth=2; else if (depth_4_ok && mng_info->write_png_depth <= 4) ping_bit_depth=4; } } image_depth=ping_bit_depth; } else if (mng_info->IsPalette) { number_colors=image_colors; if (image_depth <= 8) { /* Set image palette. */ ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE; if (!(mng_info->have_write_global_plte && matte == MagickFalse)) { for (i=0; i < (ssize_t) number_colors; i++) { palette[i].red=ScaleQuantumToChar(image->colormap[i].red); palette[i].green=ScaleQuantumToChar(image->colormap[i].green); palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up PLTE chunk with %d colors", number_colors); ping_have_PLTE=MagickTrue; } /* color_type is PNG_COLOR_TYPE_PALETTE */ if (mng_info->write_png_depth == 0) { size_t one; ping_bit_depth=1; one=1; while ((one << ping_bit_depth) < (size_t) number_colors) ping_bit_depth <<= 1; } ping_num_trans=0; if (matte != MagickFalse) { /* * Set up trans_colors array. */ assert(number_colors <= 256); ping_num_trans=(unsigned short) (number_transparent + number_semitransparent); if (ping_num_trans == 0) ping_have_tRNS=MagickFalse; else { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color (1)"); } ping_have_tRNS=MagickTrue; for (i=0; i < ping_num_trans; i++) { ping_trans_alpha[i]= (png_byte) (255- ScaleQuantumToChar(image->colormap[i].opacity)); } } } } } else { if (image_depth < 8) image_depth=8; if ((save_image_depth == 16) && (image_depth == 8)) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color from (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } ping_trans_color.red*=0x0101; ping_trans_color.green*=0x0101; ping_trans_color.blue*=0x0101; ping_trans_color.gray*=0x0101; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to (%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } if (ping_bit_depth < (ssize_t) mng_info->write_png_depth) ping_bit_depth = (ssize_t) mng_info->write_png_depth; /* Adjust background and transparency samples in sub-8-bit grayscale files. */ if (ping_bit_depth < 8 && ping_color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 maxval; size_t one=1; maxval=(png_uint_16) ((one << ping_bit_depth)-1); if (ping_exclude_bKGD == MagickFalse) { ping_background.gray=(png_uint_16) ((maxval/65535.)*(ScaleQuantumToShort((Quantum) GetPixelLuma(image,&image->background_color)))+.5); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk (2)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.index is %d", (int) ping_background.index); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_background.gray is %d", (int) ping_background.gray); } ping_have_bKGD = MagickTrue; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scaling ping_trans_color.gray from %d", (int)ping_trans_color.gray); ping_trans_color.gray=(png_uint_16) ((maxval/255.)*( ping_trans_color.gray)+.5); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " to %d", (int)ping_trans_color.gray); } if (ping_exclude_bKGD == MagickFalse) { if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE) { /* Identify which colormap entry is the background color. */ number_colors=image_colors; for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++) if (IsPNGColorEqual(image->background_color,image->colormap[i])) break; ping_background.index=(png_byte) i; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk with index=%d",(int) i); } if (i < (ssize_t) number_colors) { ping_have_bKGD = MagickTrue; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background =(%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); } } else /* Can't happen */ { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No room in PLTE to add bKGD color"); ping_have_bKGD = MagickFalse; } } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color type: %s (%d)", PngColorTypeToString(ping_color_type), ping_color_type); /* Initialize compression level and filtering. */ if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up deflate compression"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression buffer size: 32768"); } png_set_compression_buffer_size(ping,32768L); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression mem level: 9"); png_set_compression_mem_level(ping, 9); /* Untangle the "-quality" setting: Undefined is 0; the default is used. Default is 75 10's digit: 0 or omitted: Use Z_HUFFMAN_ONLY strategy with the zlib default compression level 1-9: the zlib compression level 1's digit: 0-4: the PNG filter method 5: libpng adaptive filtering if compression level > 5 libpng filter type "none" if compression level <= 5 or if image is grayscale or palette 6: libpng adaptive filtering 7: "LOCO" filtering (intrapixel differing) if writing a MNG, otherwise "none". Did not work in IM-6.7.0-9 and earlier because of a missing "else". 8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive filtering. Unused prior to IM-6.7.0-10, was same as 6 9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters Unused prior to IM-6.7.0-10, was same as 6 Note that using the -quality option, not all combinations of PNG filter type, zlib compression level, and zlib compression strategy are possible. This is addressed by using "-define png:compression-strategy", etc., which takes precedence over -quality. */ quality=image_info->quality == UndefinedCompressionQuality ? 75UL : image_info->quality; if (quality <= 9) { if (mng_info->write_png_compression_strategy == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; } else if (mng_info->write_png_compression_level == 0) { int level; level=(int) MagickMin((ssize_t) quality/10,9); mng_info->write_png_compression_level = level+1; } if (mng_info->write_png_compression_strategy == 0) { if ((quality %10) == 8 || (quality %10) == 9) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy=Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif } if (mng_info->write_png_compression_filter == 0) mng_info->write_png_compression_filter=((int) quality % 10) + 1; if (logging != MagickFalse) { if (mng_info->write_png_compression_level) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression level: %d", (int) mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_strategy) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression strategy: %d", (int) mng_info->write_png_compression_strategy-1); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up filtering"); if (mng_info->write_png_compression_filter == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: ADAPTIVE"); else if (mng_info->write_png_compression_filter == 0 || mng_info->write_png_compression_filter == 1) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: NONE"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Base filter method: %d", (int) mng_info->write_png_compression_filter-1); } if (mng_info->write_png_compression_level != 0) png_set_compression_level(ping,mng_info->write_png_compression_level-1); if (mng_info->write_png_compression_filter == 6) { if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) || ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) || (quality < 50)) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); } else if (mng_info->write_png_compression_filter == 7 || mng_info->write_png_compression_filter == 10) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS); else if (mng_info->write_png_compression_filter == 8) { #if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING) if (mng_info->write_mng) { if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) || ((int) ping_color_type == PNG_COLOR_TYPE_RGBA)) ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING; } #endif png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); } else if (mng_info->write_png_compression_filter == 9) png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS); else if (mng_info->write_png_compression_filter != 0) png_set_filter(ping,PNG_FILTER_TYPE_BASE, mng_info->write_png_compression_filter-1); if (mng_info->write_png_compression_strategy != 0) png_set_compression_strategy(ping, mng_info->write_png_compression_strategy-1); ping_interlace_method=image_info->interlace != NoInterlace; if (mng_info->write_mng) png_set_sig_bytes(ping,8); /* Bail out if cannot meet defined png:bit-depth or png:color-type */ if (mng_info->write_png_colortype != 0) { if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY) if (ping_have_color != MagickFalse) { ping_color_type = PNG_COLOR_TYPE_RGB; if (ping_bit_depth < 8) ping_bit_depth=8; } if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA) if (ping_have_color != MagickFalse) ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA; } if (ping_need_colortype_warning != MagickFalse || ((mng_info->write_png_depth && (int) mng_info->write_png_depth != ping_bit_depth) || (mng_info->write_png_colortype && ((int) mng_info->write_png_colortype-1 != ping_color_type && mng_info->write_png_colortype != 7 && !(mng_info->write_png_colortype == 5 && ping_color_type == 0))))) { if (logging != MagickFalse) { if (ping_need_colortype_warning != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image has transparency but tRNS chunk was excluded"); } if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth=%u, Computed depth=%u", mng_info->write_png_depth, ping_bit_depth); } if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type=%u, Computed color type=%u", mng_info->write_png_colortype-1, ping_color_type); } } png_warning(ping, "Cannot write image with defined png:bit-depth or png:color-type."); } if (image_matte != MagickFalse && image->matte == MagickFalse) { /* Add an opaque matte channel */ image->matte = MagickTrue; (void) SetImageOpacity(image,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Added an opaque matte channel"); } if (number_transparent != 0 || number_semitransparent != 0) { if (ping_color_type < 4) { ping_have_tRNS=MagickTrue; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting ping_have_tRNS=MagickTrue."); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG header chunks"); png_set_IHDR(ping,ping_info,ping_width,ping_height, ping_bit_depth,ping_color_type, ping_interlace_method,ping_compression_method, ping_filter_method); if (ping_color_type == 3 && ping_have_PLTE != MagickFalse) { if (mng_info->have_write_global_plte && matte == MagickFalse) { png_set_PLTE(ping,ping_info,NULL,0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up empty PLTE chunk"); } else png_set_PLTE(ping,ping_info,palette,number_colors); if (logging != MagickFalse) { for (i=0; i< (ssize_t) number_colors; i++) { if (i < ping_num_trans) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue, (int) i, (int) ping_trans_alpha[i]); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PLTE[%d] = (%d,%d,%d)", (int) i, (int) palette[i].red, (int) palette[i].green, (int) palette[i].blue); } } } /* Only write the iCCP chunk if we are not writing the sRGB chunk. */ if (ping_exclude_sRGB != MagickFalse || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if ((ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) && (ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse)) { ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { #ifdef PNG_WRITE_iCCP_SUPPORTED if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { if (ping_exclude_iCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up iCCP chunk"); png_set_iCCP(ping,ping_info,(const png_charp) name,0, #if (PNG_LIBPNG_VER < 10500) (png_charp) GetStringInfoDatum(profile), #else (const png_byte *) GetStringInfoDatum(profile), #endif (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } else #endif if (ping_exclude_zCCP == MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up zTXT chunk with uuencoded ICC"); Magick_png_write_raw_profile(image_info,ping,ping_info, (unsigned char *) name,(unsigned char *) name, GetStringInfoDatum(profile), (png_uint_32) GetStringInfoLength(profile)); ping_have_iCCP = MagickTrue; } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk with %s profile",name); name=GetNextImageProfile(image); } } } #if defined(PNG_WRITE_sRGB_SUPPORTED) if ((mng_info->have_write_global_srgb == 0) && ping_have_iCCP != MagickTrue && (ping_have_sRGB != MagickFalse || png_get_valid(ping,ping_info,PNG_INFO_sRGB))) { if (ping_exclude_sRGB == MagickFalse) { /* Note image rendering intent. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up sRGB chunk"); (void) png_set_sRGB(ping,ping_info,( Magick_RenderingIntent_to_PNG_RenderingIntent( image->rendering_intent))); ping_have_sRGB = MagickTrue; } } if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB))) #endif { if (ping_exclude_gAMA == MagickFalse && ping_have_iCCP == MagickFalse && ping_have_sRGB == MagickFalse && (ping_exclude_sRGB == MagickFalse || (image->gamma < .45 || image->gamma > .46))) { if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0)) { /* Note image gamma. To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up gAMA chunk"); png_set_gAMA(ping,ping_info,image->gamma); } } if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse) { if ((mng_info->have_write_global_chrm == 0) && (image->chromaticity.red_primary.x != 0.0)) { /* Note image chromaticity. Note: if cHRM+gAMA == sRGB write sRGB instead. */ PrimaryInfo bp, gp, rp, wp; wp=image->chromaticity.white_point; rp=image->chromaticity.red_primary; gp=image->chromaticity.green_primary; bp=image->chromaticity.blue_primary; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up cHRM chunk"); png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y, bp.x,bp.y); } } } if (ping_exclude_bKGD == MagickFalse) { if (ping_have_bKGD != MagickFalse) { png_set_bKGD(ping,ping_info,&ping_background); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up bKGD chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " background color = (%d,%d,%d)", (int) ping_background.red, (int) ping_background.green, (int) ping_background.blue); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " index = %d, gray=%d", (int) ping_background.index, (int) ping_background.gray); } } } if (ping_exclude_pHYs == MagickFalse) { if (ping_have_pHYs != MagickFalse) { png_set_pHYs(ping,ping_info, ping_pHYs_x_resolution, ping_pHYs_y_resolution, ping_pHYs_unit_type); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up pHYs chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_resolution=%lu", (unsigned long) ping_pHYs_x_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " y_resolution=%lu", (unsigned long) ping_pHYs_y_resolution); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unit_type=%lu", (unsigned long) ping_pHYs_unit_type); } } } #if defined(PNG_tIME_SUPPORTED) if (ping_exclude_tIME == MagickFalse) { const char *timestamp; if (image->taint == MagickFalse) { timestamp=GetImageOption(image_info,"png:tIME"); if (timestamp == (const char *) NULL) timestamp=GetImageProperty(image,"png:tIME"); } else { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reset tIME in tainted image"); timestamp=GetImageProperty(image,"date:modify"); } if (timestamp != (const char *) NULL) write_tIME_chunk(image,ping,ping_info,timestamp); } #endif if (mng_info->need_blob != MagickFalse) { if (OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception) == MagickFalse) png_error(ping,"WriteBlob Failed"); ping_have_blob=MagickTrue; (void) ping_have_blob; } png_write_info_before_PLTE(ping, ping_info); if (ping_have_tRNS != MagickFalse && ping_color_type < 4) { if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Calling png_set_tRNS with num_trans=%d",ping_num_trans); } if (ping_color_type == 3) (void) png_set_tRNS(ping, ping_info, ping_trans_alpha, ping_num_trans, NULL); else { (void) png_set_tRNS(ping, ping_info, NULL, 0, &ping_trans_color); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS color =(%d,%d,%d)", (int) ping_trans_color.red, (int) ping_trans_color.green, (int) ping_trans_color.blue); } } } /* write any png-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging); png_write_info(ping,ping_info); /* write any PNG-chunk-m profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging); ping_wrote_caNv = MagickFalse; /* write caNv chunk */ if (ping_exclude_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows) || image->page.x != 0 || image->page.y != 0) { unsigned char chunk[20]; (void) WriteBlobMSBULong(image,16L); /* data length=8 */ PNGType(chunk,mng_caNv); LogPNGChunk(logging,mng_caNv,16L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); PNGsLong(chunk+12,(png_int_32) image->page.x); PNGsLong(chunk+16,(png_int_32) image->page.y); (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); ping_wrote_caNv = MagickTrue; } } #if defined(PNG_oFFs_SUPPORTED) if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse) { if (image->page.x || image->page.y) { png_set_oFFs(ping,ping_info,(png_int_32) image->page.x, (png_int_32) image->page.y, 0); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up oFFs chunk with x=%d, y=%d, units=0", (int) image->page.x, (int) image->page.y); } } #endif /* write vpAg chunk (deprecated, replaced by caNv) */ if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse) { if ((image->page.width != 0 && image->page.width != image->columns) || (image->page.height != 0 && image->page.height != image->rows)) { unsigned char chunk[14]; (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } } #if (PNG_LIBPNG_VER == 10206) /* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */ #define PNG_HAVE_IDAT 0x04 ping->mode |= PNG_HAVE_IDAT; #undef PNG_HAVE_IDAT #endif png_set_packing(ping); /* Allocate memory. */ rowbytes=image->columns; if (image_depth > 8) rowbytes*=2; switch (ping_color_type) { case PNG_COLOR_TYPE_RGB: rowbytes*=3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: rowbytes*=2; break; case PNG_COLOR_TYPE_RGBA: rowbytes*=4; break; default: break; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocating %.20g bytes of memory for pixels",(double) rowbytes); } pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels)); if (pixel_info == (MemoryInfo *) NULL) png_error(ping,"Allocation of memory for pixels failed"); ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Initialize image scanlines. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) png_error(ping,"Memory allocation for quantum_info failed"); quantum_info->format=UndefinedQuantumFormat; SetQuantumDepth(image,quantum_info,image_depth); (void) SetQuantumEndian(image,quantum_info,MSBEndian); num_passes=png_set_interlace_handling(ping); if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (mng_info->IsPalette || (image_info->type == BilevelType)) && image_matte == MagickFalse && ping_have_non_bw == MagickFalse) { /* Palette, Bilevel, or Opaque Monochrome */ register const PixelPacket *p; SetQuantumDepth(image,quantum_info,8); for (pass=0; pass < num_passes; pass++) { /* Convert PseudoClass image to a PNG monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (0)"); p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (mng_info->IsPalette) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE && mng_info->write_png_depth && mng_info->write_png_depth != old_bit_depth) { /* Undo pixel scaling */ for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) (*(ping_pixels+i) >> (8-old_bit_depth)); } } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); } if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE) for (i=0; i < (ssize_t) image->columns; i++) *(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ? 255 : 0); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (1)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else /* Not Palette, Bilevel, or Opaque Monochrome */ { if ((!mng_info->write_png8 && !mng_info->write_png24 && !mng_info->write_png48 && !mng_info->write_png64 && !mng_info->write_png32) && (image_matte != MagickFalse || (ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) && (mng_info->IsPalette) && ping_have_color == MagickFalse) { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { 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; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (mng_info->IsPalette) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY PNG pixels (2)"); } else /* PNG_COLOR_TYPE_GRAY_ALPHA */ { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (2)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels,&image->exception); } if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (2)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } else { register const PixelPacket *p; for (pass=0; pass < num_passes; pass++) { if ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) { 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; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { if (image->storage_class == DirectClass) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (3)"); } else if (image_matte != MagickFalse) (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBAQuantum,ping_pixels,&image->exception); else (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RGBQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of pixels (3)"); png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } else /* not ((image_depth > 8) || mng_info->write_png24 || mng_info->write_png32 || mng_info->write_png48 || mng_info->write_png64 || (!mng_info->write_png8 && !mng_info->IsPalette)) */ { if ((ping_color_type != PNG_COLOR_TYPE_GRAY) && (ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is not GRAY or GRAY_ALPHA",pass); SetQuantumDepth(image,quantum_info,8); image_depth=8; } for (y=0; y < (ssize_t) image->rows; y++) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",pass); p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; if (ping_color_type == PNG_COLOR_TYPE_GRAY) { SetQuantumDepth(image,quantum_info,image->depth); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,ping_pixels,&image->exception); } else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (logging != MagickFalse && y == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GRAY_ALPHA PNG pixels (4)"); (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayAlphaQuantum,ping_pixels, &image->exception); } else { (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,IndexQuantum,ping_pixels,&image->exception); if (logging != MagickFalse && y <= 2) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing row of non-gray pixels (4)"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ping_pixels[0]=%d,ping_pixels[1]=%d", (int)ping_pixels[0],(int)ping_pixels[1]); } } png_write_row(ping,ping_pixels); status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) (pass * image->rows + y), num_passes * image->rows); if (status == MagickFalse) break; } } } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Wrote PNG image data"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Width: %.20g",(double) ping_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Height: %.20g",(double) ping_height); if (mng_info->write_png_depth) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:bit-depth: %d",mng_info->write_png_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG bit-depth written: %d",ping_bit_depth); if (mng_info->write_png_colortype) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Defined png:color-type: %d",mng_info->write_png_colortype-1); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG color-type written: %d",ping_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " PNG Interlace method: %d",ping_interlace_method); } /* Generate text chunks after IDAT. */ if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { png_textp text; value=GetImageProperty(image,property); /* Don't write any "png:" or "jpeg:" properties; those are just for * "identify" or for passing through to another JPEG */ if ((LocaleNCompare(property,"png:",4) != 0 && LocaleNCompare(property,"jpeg:",5) != 0) && /* Suppress density and units if we wrote a pHYs chunk */ (ping_exclude_pHYs != MagickFalse || LocaleCompare(property,"density") != 0 || LocaleCompare(property,"units") != 0) && /* Suppress the IM-generated Date:create and Date:modify */ (ping_exclude_date == MagickFalse || LocaleNCompare(property, "Date:",5) != 0)) { if (value != (const char *) NULL) { #if PNG_LIBPNG_VER >= 10400 text=(png_textp) png_malloc(ping, (png_alloc_size_t) sizeof(png_text)); #else text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text)); #endif text[0].key=(char *) property; text[0].text=(char *) value; text[0].text_length=strlen(value); if (ping_exclude_tEXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_zTXt; else if (ping_exclude_zTXt != MagickFalse) text[0].compression=PNG_TEXT_COMPRESSION_NONE; else { text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE : PNG_TEXT_COMPRESSION_zTXt ; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Setting up text chunk"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " keyword: '%s'",text[0].key); } png_set_text(ping,ping_info,text,1); png_free(ping,text); } } property=GetNextImageProperty(image); } } /* write any PNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging); /* write exIf profile */ if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse) { char *name; ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { if (LocaleCompare(name,"exif") == 0) { const StringInfo *profile; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { png_uint_32 length; unsigned char chunk[4], *data; StringInfo *ping_profile; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Have eXIf profile"); ping_profile=CloneStringInfo(profile); data=GetStringInfoDatum(ping_profile), length=(png_uint_32) GetStringInfoLength(ping_profile); #if 0 /* eXIf chunk is registered */ PNGType(chunk,mng_eXIf); #else /* eXIf chunk not yet registered; write exIf instead */ PNGType(chunk,mng_exIf); #endif if (length < 7) break; /* othewise crashes */ /* skip the "Exif\0\0" JFIF Exif Header ID */ length -= 6; LogPNGChunk(logging,chunk,length); (void) WriteBlobMSBULong(image,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,data+6); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data+6, (uInt) length)); break; } } name=GetNextImageProfile(image); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG end info"); png_write_end(ping,ping_info); if (mng_info->need_fram && (int) image->dispose == BackgroundDispose) { if (mng_info->page.x || mng_info->page.y || (ping_width != mng_info->page.width) || (ping_height != mng_info->page.height)) { unsigned char chunk[32]; /* Write FRAM 4 with clipping boundaries followed by FRAM 1. */ (void) WriteBlobMSBULong(image,27L); /* data length=27 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,27L); chunk[4]=4; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=1; /* flag for changing delay, for next frame only */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=1; /* flag for changing frame clipping for next frame */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */ chunk[14]=0; /* clipping boundaries delta type */ PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */ PNGLong(chunk+19, (png_uint_32) (mng_info->page.x + ping_width)); PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */ PNGLong(chunk+27, (png_uint_32) (mng_info->page.y + ping_height)); (void) WriteBlob(image,31,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,31)); mng_info->old_framing_mode=4; mng_info->framing_mode=1; } else mng_info->framing_mode=3; } if (mng_info->write_mng && !mng_info->need_fram && ((int) image->dispose == 3)) png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC"); /* Free PNG resources. */ png_destroy_write_struct(&ping,&ping_info); pixel_info=RelinquishVirtualMemory(pixel_info); /* Store bit depth actually written */ s[0]=(char) ping_bit_depth; s[1]='\0'; (void) SetImageProperty(image,"png:bit-depth-written",s); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOnePNGImage()"); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE UnlockSemaphoreInfo(ping_semaphore); #endif /* } for navigation to beginning of SETJMP-protected block. Revert to * Throwing an Exception when an error occurs. */ return(MagickTrue); /* End write one PNG image */ } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNGImage() writes a Portable Network Graphics (PNG) or % Multiple-image Network Graphics (MNG) image file. % % MNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WritePNGImage method is: % % MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % % Returns MagickTrue on success, MagickFalse on failure. % % Communicating with the PNG encoder: % % While the datastream written is always in PNG format and normally would % be given the "png" file extension, this method also writes the following % pseudo-formats which are subsets of png: % % o PNG8: An 8-bit indexed PNG datastream is written. If the image has % a depth greater than 8, the depth is reduced. If transparency % is present, the tRNS chunk must only have values 0 and 255 % (i.e., transparency is binary: fully opaque or fully % transparent). If other values are present they will be % 50%-thresholded to binary transparency. If more than 256 % colors are present, they will be quantized to the 4-4-4-1, % 3-3-3-1, or 3-3-2-1 palette. The underlying RGB color % of any resulting fully-transparent pixels is changed to % the image's background color. % % If you want better quantization or dithering of the colors % or alpha than that, you need to do it before calling the % PNG encoder. The pixels contain 8-bit indices even if % they could be represented with 1, 2, or 4 bits. Grayscale % images will be written as indexed PNG files even though the % PNG grayscale type might be slightly more efficient. Please % note that writing to the PNG8 format may result in loss % of color and alpha data. % % o PNG24: An 8-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. The only loss incurred % is reduction of sample depth to 8. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG32: An 8-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 255. The alpha % channel is present even if the image is fully opaque. % The only loss in data is the reduction of the sample depth % to 8. % % o PNG48: A 16-bit per sample RGB PNG datastream is written. The tRNS % chunk can be present to convey binary transparency by naming % one of the colors as transparent. If the image has more % than one transparent color, has semitransparent pixels, or % has an opaque pixel with the same RGB components as the % transparent color, an image is not written. % % o PNG64: A 16-bit per sample RGBA PNG is written. Partial % transparency is permitted, i.e., the alpha sample for % each pixel can have any value from 0 to 65535. The alpha % channel is present even if the image is fully opaque. % % o PNG00: A PNG that inherits its colortype and bit-depth from the input % image, if the input was a PNG, is written. If these values % cannot be found, or if the pixels have been changed in a way % that makes this impossible, then "PNG00" falls back to the % regular "PNG" format. % % o -define: For more precise control of the PNG output, you can use the % Image options "png:bit-depth" and "png:color-type". These % can be set from the commandline with "-define" and also % from the application programming interfaces. The options % are case-independent and are converted to lowercase before % being passed to this encoder. % % png:color-type can be 0, 2, 3, 4, or 6. % % When png:color-type is 0 (Grayscale), png:bit-depth can % be 1, 2, 4, 8, or 16. % % When png:color-type is 2 (RGB), png:bit-depth can % be 8 or 16. % % When png:color-type is 3 (Indexed), png:bit-depth can % be 1, 2, 4, or 8. This refers to the number of bits % used to store the index. The color samples always have % bit-depth 8 in indexed PNG files. % % When png:color-type is 4 (Gray-Matte) or 6 (RGB-Matte), % png:bit-depth can be 8 or 16. % % If the image cannot be written without loss with the % requested bit-depth and color-type, a PNG file will not % be written, a warning will be issued, and the encoder will % return MagickFalse. % % Since image encoders should not be responsible for the "heavy lifting", % the user should make sure that ImageMagick has already reduced the % image depth and number of colors and limit transparency to binary % transparency prior to attempting to write the image with depth, color, % or transparency limitations. % % To do: Enforce the previous paragraph. % % Note that another definition, "png:bit-depth-written" exists, but it % is not intended for external use. It is only used internally by the % PNG encoder to inform the JNG encoder of the depth of the alpha channel. % % It is possible to request that the PNG encoder write previously-formatted % ancillary chunks in the output PNG file, using the "-profile" commandline % option as shown below or by setting the profile via a programming % interface: % % -profile PNG-chunk-x:<file> % % where x is a location flag and <file> is a file containing the chunk % name in the first 4 bytes, then a colon (":"), followed by the chunk data. % This encoder will compute the chunk length and CRC, so those must not % be included in the file. % % "x" can be "b" (before PLTE), "m" (middle, i.e., between PLTE and IDAT), % or "e" (end, i.e., after IDAT). If you want to write multiple chunks % of the same type, then add a short unique string after the "x" to prevent % subsequent profiles from overwriting the preceding ones, e.g., % % -profile PNG-chunk-b01:file01 -profile PNG-chunk-b02:file02 % % As of version 6.6.6 the following optimizations are always done: % % o 32-bit depth is reduced to 16. % o 16-bit depth is reduced to 8 if all pixels contain samples whose % high byte and low byte are identical. % o Palette is sorted to remove unused entries and to put a % transparent color first, if BUILD_PNG_PALETTE is defined. % o Opaque matte channel is removed when writing an indexed PNG. % o Grayscale images are reduced to 1, 2, or 4 bit depth if % this can be done without loss and a larger bit depth N was not % requested via the "-define png:bit-depth=N" option. % o If matte channel is present but only one transparent color is % present, RGB+tRNS is written instead of RGBA % o Opaque matte channel is removed (or added, if color-type 4 or 6 % was requested when converting an opaque image). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType excluding, logging, status; MngInfo *mng_info; const char *value; int source; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WritePNGImage()"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; mng_info->equal_backgrounds=MagickTrue; /* See if user has requested a specific PNG subformat */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; mng_info->write_png48=LocaleCompare(image_info->magick,"PNG48") == 0; mng_info->write_png64=LocaleCompare(image_info->magick,"PNG64") == 0; value=GetImageOption(image_info,"png:format"); if (value != (char *) NULL || LocaleCompare(image_info->magick,"PNG00") == 0) { mng_info->write_png8 = MagickFalse; mng_info->write_png24 = MagickFalse; mng_info->write_png32 = MagickFalse; mng_info->write_png48 = MagickFalse; mng_info->write_png64 = MagickFalse; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",value); if (LocaleCompare(value,"png8") == 0) mng_info->write_png8 = MagickTrue; else if (LocaleCompare(value,"png24") == 0) mng_info->write_png24 = MagickTrue; else if (LocaleCompare(value,"png32") == 0) mng_info->write_png32 = MagickTrue; else if (LocaleCompare(value,"png48") == 0) mng_info->write_png48 = MagickTrue; else if (LocaleCompare(value,"png64") == 0) mng_info->write_png64 = MagickTrue; else if ((LocaleCompare(value,"png00") == 0) || LocaleCompare(image_info->magick,"PNG00") == 0) { /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ value=GetImageProperty(image,"png:IHDR.bit-depth-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited bit depth=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; } value=GetImageProperty(image,"png:IHDR.color-type-orig"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png00 inherited color type=%s",value); if (value != (char *) NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; } } } if (mng_info->write_png8) { mng_info->write_png_colortype = /* 3 */ 4; mng_info->write_png_depth = 8; image->depth = 8; } if (mng_info->write_png24) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 8; image->depth = 8; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png32) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 8; image->depth = 8; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } if (mng_info->write_png48) { mng_info->write_png_colortype = /* 2 */ 3; mng_info->write_png_depth = 16; image->depth = 16; if (image->matte != MagickFalse) (void) SetImageType(image,TrueColorMatteType); else (void) SetImageType(image,TrueColorType); (void) SyncImage(image); } if (mng_info->write_png64) { mng_info->write_png_colortype = /* 6 */ 7; mng_info->write_png_depth = 16; image->depth = 16; image->matte = MagickTrue; (void) SetImageType(image,TrueColorMatteType); (void) SyncImage(image); } value=GetImageOption(image_info,"png:bit-depth"); if (value != (char *) NULL) { if (LocaleCompare(value,"1") == 0) mng_info->write_png_depth = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_depth = 2; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_depth = 4; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_depth = 8; else if (LocaleCompare(value,"16") == 0) mng_info->write_png_depth = 16; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:bit-depth", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:bit-depth=%d was defined.\n",mng_info->write_png_depth); } value=GetImageOption(image_info,"png:color-type"); if (value != (char *) NULL) { /* We must store colortype+1 because 0 is a valid colortype */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_colortype = 1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_colortype = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_colortype = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_colortype = 5; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_colortype = 7; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:color-type", "=%s",value); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:color-type=%d was defined.\n",mng_info->write_png_colortype-1); } /* Check for chunks to be excluded: * * The default is to not exclude any known chunks except for any * listed in the "unused_chunks" array, above. * * Chunks can be listed for exclusion via a "png:exclude-chunk" * define (in the image properties or in the image artifacts) * or via a mng_info member. For convenience, in addition * to or instead of a comma-separated list of chunks, the * "exclude-chunk" string can be simply "all" or "none". * * The exclude-chunk define takes priority over the mng_info. * * A "png:include-chunk" define takes priority over both the * mng_info and the "png:exclude-chunk" define. Like the * "exclude-chunk" string, it can define "all" or "none" as * well as a comma-separated list. Chunks that are unknown to * ImageMagick are always excluded, regardless of their "copy-safe" * status according to the PNG specification, and even if they * appear in the "include-chunk" list. Such defines appearing among * the image options take priority over those found among the image * artifacts. * * Finally, all chunks listed in the "unused_chunks" array are * automatically excluded, regardless of the other instructions * or lack thereof. * * if you exclude sRGB but not gAMA (recommended), then sRGB chunk * will not be written and the gAMA chunk will only be written if it * is not between .45 and .46, or approximately (1.0/2.2). * * If you exclude tRNS and the image has transparency, the colortype * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). * * The -strip option causes StripImage() to set the png:include-chunk * artifact to "none,trns,gama". */ mng_info->ping_exclude_bKGD=MagickFalse; mng_info->ping_exclude_caNv=MagickFalse; mng_info->ping_exclude_cHRM=MagickFalse; mng_info->ping_exclude_date=MagickFalse; mng_info->ping_exclude_eXIf=MagickFalse; mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ mng_info->ping_exclude_gAMA=MagickFalse; mng_info->ping_exclude_iCCP=MagickFalse; /* mng_info->ping_exclude_iTXt=MagickFalse; */ mng_info->ping_exclude_oFFs=MagickFalse; mng_info->ping_exclude_pHYs=MagickFalse; mng_info->ping_exclude_sRGB=MagickFalse; mng_info->ping_exclude_tEXt=MagickFalse; mng_info->ping_exclude_tIME=MagickFalse; mng_info->ping_exclude_tRNS=MagickFalse; mng_info->ping_exclude_vpAg=MagickFalse; mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ mng_info->ping_exclude_zTXt=MagickFalse; mng_info->ping_preserve_colormap=MagickFalse; value=GetImageOption(image_info,"png:preserve-colormap"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-colormap"); if (value != NULL) mng_info->ping_preserve_colormap=MagickTrue; mng_info->ping_preserve_iCCP=MagickFalse; value=GetImageOption(image_info,"png:preserve-iCCP"); if (value == NULL) value=GetImageArtifact(image,"png:preserve-iCCP"); if (value != NULL) mng_info->ping_preserve_iCCP=MagickTrue; /* These compression-level, compression-strategy, and compression-filter * defines take precedence over values from the -quality option. */ value=GetImageOption(image_info,"png:compression-level"); if (value == NULL) value=GetImageArtifact(image,"png:compression-level"); if (value != NULL) { /* To do: use a "LocaleInteger:()" function here. */ /* We have to add 1 to everything because 0 is a valid input, * and we want to use 0 (the default) to mean undefined. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_level = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_level = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_level = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_level = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_level = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_level = 6; else if (LocaleCompare(value,"6") == 0) mng_info->write_png_compression_level = 7; else if (LocaleCompare(value,"7") == 0) mng_info->write_png_compression_level = 8; else if (LocaleCompare(value,"8") == 0) mng_info->write_png_compression_level = 9; else if (LocaleCompare(value,"9") == 0) mng_info->write_png_compression_level = 10; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-level", "=%s",value); } value=GetImageOption(image_info,"png:compression-strategy"); if (value == NULL) value=GetImageArtifact(image,"png:compression-strategy"); if (value != NULL) { if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_strategy = Z_FILTERED+1; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; else if (LocaleCompare(value,"3") == 0) #ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ mng_info->write_png_compression_strategy = Z_RLE+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else if (LocaleCompare(value,"4") == 0) #ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ mng_info->write_png_compression_strategy = Z_FIXED+1; #else mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; #endif else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-strategy", "=%s",value); } value=GetImageOption(image_info,"png:compression-filter"); if (value == NULL) value=GetImageArtifact(image,"png:compression-filter"); if (value != NULL) { /* To do: combinations of filters allowed by libpng * masks 0x08 through 0xf8 * * Implement this as a comma-separated list of 0,1,2,3,4,5 * where 5 is a special case meaning PNG_ALL_FILTERS. */ if (LocaleCompare(value,"0") == 0) mng_info->write_png_compression_filter = 1; else if (LocaleCompare(value,"1") == 0) mng_info->write_png_compression_filter = 2; else if (LocaleCompare(value,"2") == 0) mng_info->write_png_compression_filter = 3; else if (LocaleCompare(value,"3") == 0) mng_info->write_png_compression_filter = 4; else if (LocaleCompare(value,"4") == 0) mng_info->write_png_compression_filter = 5; else if (LocaleCompare(value,"5") == 0) mng_info->write_png_compression_filter = 6; else (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "ignoring invalid defined png:compression-filter", "=%s",value); } for (source=0; source<8; source++) { value = NULL; if (source == 0) value=GetImageOption(image_info,"png:exclude-chunks"); if (source == 1) value=GetImageArtifact(image,"png:exclude-chunks"); if (source == 2) value=GetImageOption(image_info,"png:exclude-chunk"); if (source == 3) value=GetImageArtifact(image,"png:exclude-chunk"); if (source == 4) value=GetImageOption(image_info,"png:include-chunks"); if (source == 5) value=GetImageArtifact(image,"png:include-chunks"); if (source == 6) value=GetImageOption(image_info,"png:include-chunk"); if (source == 7) value=GetImageArtifact(image,"png:include-chunk"); if (value == NULL) continue; if (source < 4) excluding = MagickTrue; else excluding = MagickFalse; if (logging != MagickFalse) { if (source == 0 || source == 2) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image options.\n", value); else if (source == 1 || source == 3) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:exclude-chunk=%s found in image artifacts.\n", value); else if (source == 4 || source == 6) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image options.\n", value); else /* if (source == 5 || source == 7) */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " png:include-chunk=%s found in image artifacts.\n", value); } if (IsOptionMember("all",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding; mng_info->ping_exclude_caNv=excluding; mng_info->ping_exclude_cHRM=excluding; mng_info->ping_exclude_date=excluding; mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; mng_info->ping_exclude_gAMA=excluding; mng_info->ping_exclude_iCCP=excluding; /* mng_info->ping_exclude_iTXt=excluding; */ mng_info->ping_exclude_oFFs=excluding; mng_info->ping_exclude_pHYs=excluding; mng_info->ping_exclude_sRGB=excluding; mng_info->ping_exclude_tIME=excluding; mng_info->ping_exclude_tEXt=excluding; mng_info->ping_exclude_tRNS=excluding; mng_info->ping_exclude_vpAg=excluding; mng_info->ping_exclude_zCCP=excluding; mng_info->ping_exclude_zTXt=excluding; } if (IsOptionMember("none",value) != MagickFalse) { mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; /* mng_info->ping_exclude_iTXt=!excluding; */ mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_vpAg=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : MagickTrue; mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : MagickTrue; } if (IsOptionMember("bkgd",value) != MagickFalse) mng_info->ping_exclude_bKGD=excluding; if (IsOptionMember("caNv",value) != MagickFalse) mng_info->ping_exclude_caNv=excluding; if (IsOptionMember("chrm",value) != MagickFalse) mng_info->ping_exclude_cHRM=excluding; if (IsOptionMember("date",value) != MagickFalse) mng_info->ping_exclude_date=excluding; if (IsOptionMember("exif",value) != MagickFalse) { mng_info->ping_exclude_EXIF=excluding; mng_info->ping_exclude_eXIf=excluding; } if (IsOptionMember("gama",value) != MagickFalse) mng_info->ping_exclude_gAMA=excluding; if (IsOptionMember("iccp",value) != MagickFalse) mng_info->ping_exclude_iCCP=excluding; #if 0 if (IsOptionMember("itxt",value) != MagickFalse) mng_info->ping_exclude_iTXt=excluding; #endif if (IsOptionMember("offs",value) != MagickFalse) mng_info->ping_exclude_oFFs=excluding; if (IsOptionMember("phys",value) != MagickFalse) mng_info->ping_exclude_pHYs=excluding; if (IsOptionMember("srgb",value) != MagickFalse) mng_info->ping_exclude_sRGB=excluding; if (IsOptionMember("text",value) != MagickFalse) mng_info->ping_exclude_tEXt=excluding; if (IsOptionMember("time",value) != MagickFalse) mng_info->ping_exclude_tIME=excluding; if (IsOptionMember("trns",value) != MagickFalse) mng_info->ping_exclude_tRNS=excluding; if (IsOptionMember("vpag",value) != MagickFalse) mng_info->ping_exclude_vpAg=excluding; if (IsOptionMember("zccp",value) != MagickFalse) mng_info->ping_exclude_zCCP=excluding; if (IsOptionMember("ztxt",value) != MagickFalse) mng_info->ping_exclude_zTXt=excluding; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Chunks to be excluded from the output png:"); if (mng_info->ping_exclude_bKGD != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bKGD"); if (mng_info->ping_exclude_caNv != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " caNv"); if (mng_info->ping_exclude_cHRM != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " cHRM"); if (mng_info->ping_exclude_date != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " date"); if (mng_info->ping_exclude_EXIF != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " EXIF"); if (mng_info->ping_exclude_eXIf != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " eXIf"); if (mng_info->ping_exclude_gAMA != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " gAMA"); if (mng_info->ping_exclude_iCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iCCP"); #if 0 if (mng_info->ping_exclude_iTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " iTXt"); #endif if (mng_info->ping_exclude_oFFs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " oFFs"); if (mng_info->ping_exclude_pHYs != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " pHYs"); if (mng_info->ping_exclude_sRGB != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " sRGB"); if (mng_info->ping_exclude_tEXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tEXt"); if (mng_info->ping_exclude_tIME != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tIME"); if (mng_info->ping_exclude_tRNS != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " tRNS"); if (mng_info->ping_exclude_vpAg != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " vpAg"); if (mng_info->ping_exclude_zCCP != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zCCP"); if (mng_info->ping_exclude_zTXt != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " zTXt"); } mng_info->need_blob = MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WritePNGImage()"); return(status); } #if defined(JNG_SUPPORTED) /* Write one JNG image */ static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info,Image *image) { Image *jpeg_image; ImageInfo *jpeg_image_info; int unique_filenames; MagickBooleanType logging, status; size_t length; unsigned char *blob, chunk[80], *p; unsigned int jng_alpha_compression_method, jng_alpha_sample_depth, jng_color_type, transparent; size_t jng_alpha_quality, jng_quality; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter WriteOneJNGImage()"); blob=(unsigned char *) NULL; jpeg_image=(Image *) NULL; jpeg_image_info=(ImageInfo *) NULL; length=0; unique_filenames=0; status=MagickTrue; transparent=image_info->type==GrayscaleMatteType || image_info->type==TrueColorMatteType || image->matte != MagickFalse; jng_alpha_sample_depth = 0; jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000; jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0; jng_alpha_quality=image_info->quality == 0UL ? 75UL : image_info->quality; if (jng_alpha_quality >= 1000) jng_alpha_quality /= 1000; if (transparent != 0) { jng_color_type=14; /* Create JPEG blob, image, and image_info */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info for opacity."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); status=SeparateImageChannel(jpeg_image,OpacityChannel); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=NegateImage(jpeg_image,MagickFalse); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_image->matte=MagickFalse; jpeg_image_info->type=GrayscaleType; jpeg_image->quality=jng_alpha_quality; (void) SetImageType(jpeg_image,GrayscaleType); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent, "%s",jpeg_image->filename); } else { jng_alpha_compression_method=0; jng_color_type=10; jng_alpha_sample_depth=0; } /* To do: check bit depth of PNG alpha channel */ /* Check if image is grayscale. */ if (image_info->type != TrueColorMatteType && image_info->type != TrueColorType && SetImageGray(image,&image->exception)) jng_color_type-=2; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Quality = %d",(int) jng_quality); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Color Type = %d",jng_color_type); if (transparent != 0) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Compression = %d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Depth = %d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG Alpha Quality = %d",(int) jng_alpha_quality); } } if (transparent != 0) { if (jng_alpha_compression_method==0) { const char *value; /* Encode opacity as a grayscale PNG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating PNG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); length=0; (void) CopyMagickString(jpeg_image_info->magick,"PNG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"PNG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; /* Exclude all ancillary chunks */ (void) SetImageArtifact(jpeg_image,"png:exclude-chunks","all"); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); /* Retrieve sample depth used */ value=GetImageProperty(jpeg_image,"png:bit-depth-written"); if (value != (char *) NULL) jng_alpha_sample_depth= (unsigned int) value[0]; } else { /* Encode opacity as a grayscale JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating JPEG blob for alpha."); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); jpeg_image_info->interlace=NoInterlace; blob=ImageToBlob(jpeg_image_info,jpeg_image,&length, &image->exception); jng_alpha_sample_depth=8; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); } /* Destroy JPEG image and image_info */ jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); } /* Write JHDR chunk */ (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */ PNGType(chunk,mng_JHDR); LogPNGChunk(logging,mng_JHDR,16L); PNGLong(chunk+4,(png_uint_32) image->columns); PNGLong(chunk+8,(png_uint_32) image->rows); chunk[12]=jng_color_type; chunk[13]=8; /* sample depth */ chunk[14]=8; /*jng_image_compression_method */ chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8); chunk[16]=jng_alpha_sample_depth; chunk[17]=jng_alpha_compression_method; chunk[18]=0; /*jng_alpha_filter_method */ chunk[19]=0; /*jng_alpha_interlace_method */ (void) WriteBlob(image,20,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,20)); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width:%15lu",(unsigned long) image->columns); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG height:%14lu",(unsigned long) image->rows); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG color type:%10d",jng_color_type); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG sample depth:%8d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG compression:%9d",8); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG interlace:%11d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha depth:%9d",jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha compression:%3d",jng_alpha_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha filter:%8d",0); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG alpha interlace:%5d",0); } /* Write any JNG-chunk-b profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-b",logging); /* Write leading ancillary chunks */ if (transparent != 0) { /* Write JNG bKGD chunk */ unsigned char blue, green, red; ssize_t num_bytes; if (jng_color_type == 8 || jng_color_type == 12) num_bytes=6L; else num_bytes=10L; (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L)); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L)); red=ScaleQuantumToChar(image->background_color.red); green=ScaleQuantumToChar(image->background_color.green); blue=ScaleQuantumToChar(image->background_color.blue); *(chunk+4)=0; *(chunk+5)=red; *(chunk+6)=0; *(chunk+7)=green; *(chunk+8)=0; *(chunk+9)=blue; (void) WriteBlob(image,(size_t) num_bytes,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes)); } if ((image->colorspace == sRGBColorspace || image->rendering_intent)) { /* Write JNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { if (image->gamma != 0.0) { /* Write JNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); } if ((mng_info->equal_chrms == MagickFalse) && (image->chromaticity.red_primary.x != 0.0)) { PrimaryInfo primary; /* Write JNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); } } if (image->x_resolution && image->y_resolution && !mng_info->equal_physs) { /* Write JNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.x || image->page.y)) { /* Write JNG oFFs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_oFFs); LogPNGChunk(logging,mng_oFFs,9L); PNGsLong(chunk+4,(ssize_t) (image->page.x)); PNGsLong(chunk+8,(ssize_t) (image->page.y)); chunk[12]=0; (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (mng_info->write_mng == 0 && (image->page.width || image->page.height)) { (void) WriteBlobMSBULong(image,9L); /* data length=8 */ PNGType(chunk,mng_vpAg); LogPNGChunk(logging,mng_vpAg,9L); PNGLong(chunk+4,(png_uint_32) image->page.width); PNGLong(chunk+8,(png_uint_32) image->page.height); chunk[12]=0; /* unit = pixels */ (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } if (transparent != 0) { if (jng_alpha_compression_method==0) { register ssize_t i; size_t len; /* Write IDAT chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write IDAT chunks from blob, length=%.20g.",(double) length); /* Copy IDAT chunks */ len=0; p=blob+8; for (i=8; i<(ssize_t) length; i+=len+12) { len=(size_t) (*p) << 24; len|=(size_t) (*(p+1)) << 16; len|=(size_t) (*(p+2)) << 8; len|=(size_t) (*(p+3)); p+=4; if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */ { /* Found an IDAT chunk. */ (void) WriteBlobMSBULong(image,len); LogPNGChunk(logging,mng_IDAT,len); (void) WriteBlob(image,len+4,p); (void) WriteBlobMSBULong(image,crc32(0,p,(uInt) len+4)); } else { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping %c%c%c%c chunk, length=%.20g.", *(p),*(p+1),*(p+2),*(p+3),(double) len); } p+=(8+len); } } else if (length != 0) { /* Write JDAA chunk header */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAA chunk, length=%.20g.",(double) length); (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAA); LogPNGChunk(logging,mng_JDAA,length); /* Write JDAT chunk(s) data */ (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob, (uInt) length)); } blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Encode image as a JPEG blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image_info."); jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info); if (jpeg_image_info == (ImageInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating jpeg_image."); jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); (void) AcquireUniqueFilename(jpeg_image->filename); unique_filenames++; (void) FormatLocaleString(jpeg_image_info->filename,MaxTextExtent,"%s", jpeg_image->filename); status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode, &image->exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Created jpeg_image, %.20g x %.20g.",(double) jpeg_image->columns, (double) jpeg_image->rows); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (jng_color_type == 8 || jng_color_type == 12) jpeg_image_info->type=GrayscaleType; jpeg_image_info->quality=jng_quality; jpeg_image->quality=jng_quality; (void) CopyMagickString(jpeg_image_info->magick,"JPEG",MaxTextExtent); (void) CopyMagickString(jpeg_image->magick,"JPEG",MaxTextExtent); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating blob."); blob=ImageToBlob(jpeg_image_info,jpeg_image,&length,&image->exception); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Successfully read jpeg_image into a blob, length=%.20g.", (double) length); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Write JDAT chunk, length=%.20g.",(double) length); } /* Write JDAT chunk(s) */ (void) WriteBlobMSBULong(image,(size_t) length); PNGType(chunk,mng_JDAT); LogPNGChunk(logging,mng_JDAT,length); (void) WriteBlob(image,4,chunk); (void) WriteBlob(image,length,blob); (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length)); jpeg_image=DestroyImage(jpeg_image); (void) RelinquishUniqueFileResource(jpeg_image_info->filename); unique_filenames--; jpeg_image_info=DestroyImageInfo(jpeg_image_info); blob=(unsigned char *) RelinquishMagickMemory(blob); /* Write any JNG-chunk-e profiles */ (void) Magick_png_write_chunk_from_profile(image,"JNG-chunk-e",logging); /* Write IEND chunk */ (void) WriteBlobMSBULong(image,0L); PNGType(chunk,mng_IEND); LogPNGChunk(logging,mng_IEND,0); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteOneJNGImage(); unique_filenames=%d",unique_filenames); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J N G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJNGImage() writes a JPEG Network Graphics (JNG) image file. % % JNG support written by Glenn Randers-Pehrson, glennrp@image... % % The format of the WriteJNGImage method is: % % MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ static MagickBooleanType WriteJNGImage(const ImageInfo *image_info,Image *image) { MagickBooleanType logging, status; MngInfo *mng_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteJNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; (void) WriteBlob(image,8,(const unsigned char *) "\213JNG\r\n\032\n"); status=WriteOneJNGImage(mng_info,image_info,image); mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); (void) CatchImageException(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit WriteJNGImage()"); return(status); } #endif static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { const char *option; Image *next_image; MagickBooleanType status; volatile MagickBooleanType logging; MngInfo *mng_info; int image_count, need_iterations, need_matte; volatile int #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) need_local_plte, #endif all_images_are_gray, need_defi, use_global_plte; register ssize_t i; unsigned char chunk[800]; volatile unsigned int write_jng, write_mng; volatile size_t scene; size_t final_delay=0, initial_delay; #if (PNG_LIBPNG_VER < 10200) if (image_info->verbose) printf("Your PNG library (libpng-%s) is rather old.\n", PNG_LIBPNG_VER_STRING); #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter WriteMNGImage()"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; write_mng=LocaleCompare(image_info->magick,"MNG") == 0; /* * See if user has requested a specific PNG subformat to be used * for all of the PNGs in the MNG being written, e.g., * * convert *.png png8:animation.mng * * To do: check -define png:bit_depth and png:color_type as well, * or perhaps use mng:bit_depth and mng:color_type instead for * global settings. */ mng_info->write_png8=LocaleCompare(image_info->magick,"PNG8") == 0; mng_info->write_png24=LocaleCompare(image_info->magick,"PNG24") == 0; mng_info->write_png32=LocaleCompare(image_info->magick,"PNG32") == 0; write_jng=MagickFalse; if (image_info->compression == JPEGCompression) write_jng=MagickTrue; mng_info->adjoin=image_info->adjoin && (GetNextImageInList(image) != (Image *) NULL) && write_mng; if (logging != MagickFalse) { /* Log some info about the input */ Image *p; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Checking input image(s)\n" " Image_info depth: %.20g, Type: %d", (double) image_info->depth, image_info->type); scene=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Scene: %.20g\n, Image depth: %.20g", (double) scene++, (double) p->depth); if (p->matte) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte: False"); if (p->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class: DirectClass"); if (p->colors) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %.20g",(double) p->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: unspecified"); if (mng_info->adjoin == MagickFalse) break; } } use_global_plte=MagickFalse; all_images_are_gray=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_defi=MagickFalse; need_matte=MagickFalse; mng_info->framing_mode=1; mng_info->old_framing_mode=1; if (write_mng) if (image_info->page != (char *) NULL) { /* Determine image bounding box. */ SetGeometry(image,&mng_info->page); (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); } if (write_mng) { unsigned int need_geom; unsigned short red, green, blue; mng_info->page=image->page; need_geom=MagickTrue; if (mng_info->page.width || mng_info->page.height) need_geom=MagickFalse; /* Check all the scenes. */ initial_delay=image->delay; need_iterations=MagickFalse; mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; mng_info->equal_physs=MagickTrue, mng_info->equal_gammas=MagickTrue; mng_info->equal_srgbs=MagickTrue; mng_info->equal_backgrounds=MagickTrue; image_count=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) all_images_are_gray=MagickTrue; mng_info->equal_palettes=MagickFalse; need_local_plte=MagickFalse; #endif for (next_image=image; next_image != (Image *) NULL; ) { if (need_geom) { if ((next_image->columns+next_image->page.x) > mng_info->page.width) mng_info->page.width=next_image->columns+next_image->page.x; if ((next_image->rows+next_image->page.y) > mng_info->page.height) mng_info->page.height=next_image->rows+next_image->page.y; } if (next_image->page.x || next_image->page.y) need_defi=MagickTrue; if (next_image->matte) need_matte=MagickTrue; if ((int) next_image->dispose >= BackgroundDispose) if (next_image->matte || next_image->page.x || next_image->page.y || ((next_image->columns < mng_info->page.width) && (next_image->rows < mng_info->page.height))) mng_info->need_fram=MagickTrue; if (next_image->iterations) need_iterations=MagickTrue; final_delay=next_image->delay; if (final_delay != initial_delay || final_delay > 1UL* next_image->ticks_per_second) mng_info->need_fram=1; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* check for global palette possibility. */ if (image->matte != MagickFalse) need_local_plte=MagickTrue; if (need_local_plte == 0) { if (SetImageGray(image,&image->exception) == MagickFalse) all_images_are_gray=MagickFalse; mng_info->equal_palettes=PalettesAreEqual(image,next_image); if (use_global_plte == 0) use_global_plte=mng_info->equal_palettes; need_local_plte=!mng_info->equal_palettes; } #endif if (GetNextImageInList(next_image) != (Image *) NULL) { if (next_image->background_color.red != next_image->next->background_color.red || next_image->background_color.green != next_image->next->background_color.green || next_image->background_color.blue != next_image->next->background_color.blue) mng_info->equal_backgrounds=MagickFalse; if (next_image->gamma != next_image->next->gamma) mng_info->equal_gammas=MagickFalse; if (next_image->rendering_intent != next_image->next->rendering_intent) mng_info->equal_srgbs=MagickFalse; if ((next_image->units != next_image->next->units) || (next_image->x_resolution != next_image->next->x_resolution) || (next_image->y_resolution != next_image->next->y_resolution)) mng_info->equal_physs=MagickFalse; if (mng_info->equal_chrms) { if (next_image->chromaticity.red_primary.x != next_image->next->chromaticity.red_primary.x || next_image->chromaticity.red_primary.y != next_image->next->chromaticity.red_primary.y || next_image->chromaticity.green_primary.x != next_image->next->chromaticity.green_primary.x || next_image->chromaticity.green_primary.y != next_image->next->chromaticity.green_primary.y || next_image->chromaticity.blue_primary.x != next_image->next->chromaticity.blue_primary.x || next_image->chromaticity.blue_primary.y != next_image->next->chromaticity.blue_primary.y || next_image->chromaticity.white_point.x != next_image->next->chromaticity.white_point.x || next_image->chromaticity.white_point.y != next_image->next->chromaticity.white_point.y) mng_info->equal_chrms=MagickFalse; } } image_count++; next_image=GetNextImageInList(next_image); } if (image_count < 2) { mng_info->equal_backgrounds=MagickFalse; mng_info->equal_chrms=MagickFalse; mng_info->equal_gammas=MagickFalse; mng_info->equal_srgbs=MagickFalse; mng_info->equal_physs=MagickFalse; use_global_plte=MagickFalse; #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED need_local_plte=MagickTrue; #endif need_iterations=MagickFalse; } if (mng_info->need_fram == MagickFalse) { /* Only certain framing rates 100/n are exactly representable without the FRAM chunk but we'll allow some slop in VLC files */ if (final_delay == 0) { if (need_iterations != MagickFalse) { /* It's probably a GIF with loop; don't run it *too* fast. */ if (mng_info->adjoin) { final_delay=10; (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderWarning, "input has zero delay between all frames; assuming", " 10 cs `%s'",""); } } else mng_info->ticks_per_second=0; } if (final_delay != 0) mng_info->ticks_per_second=(png_uint_32) (image->ticks_per_second/final_delay); if (final_delay > 50) mng_info->ticks_per_second=2; if (final_delay > 75) mng_info->ticks_per_second=1; if (final_delay > 125) mng_info->need_fram=MagickTrue; if (need_defi && final_delay > 2 && (final_delay != 4) && (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && (final_delay != 25) && (final_delay != 50) && (final_delay != (size_t) image->ticks_per_second)) mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ } if (mng_info->need_fram != MagickFalse) mng_info->ticks_per_second=1UL*image->ticks_per_second; /* If pseudocolor, we should also check to see if all the palettes are identical and write a global PLTE if they are. ../glennrp Feb 99. */ /* Write the MNG version 1.0 signature and MHDR chunk. */ (void) WriteBlob(image,8,(const unsigned char *) "\212MNG\r\n\032\n"); (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ PNGType(chunk,mng_MHDR); LogPNGChunk(logging,mng_MHDR,28L); PNGLong(chunk+4,(png_uint_32) mng_info->page.width); PNGLong(chunk+8,(png_uint_32) mng_info->page.height); PNGLong(chunk+12,mng_info->ticks_per_second); PNGLong(chunk+16,0L); /* layer count=unknown */ PNGLong(chunk+20,0L); /* frame count=unknown */ PNGLong(chunk+24,0L); /* play time=unknown */ if (write_jng) { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ else PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ else PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ } } else { if (need_matte) { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,11L); /* simplicity=LC */ else PNGLong(chunk+28,9L); /* simplicity=VLC */ } else { if (need_defi || mng_info->need_fram || use_global_plte) PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ else PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ } } (void) WriteBlob(image,32,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); option=GetImageOption(image_info,"mng:need-cacheoff"); if (option != (const char *) NULL) { size_t length; /* Write "nEED CACHEOFF" to turn playback caching off for streaming MNG. */ PNGType(chunk,mng_nEED); length=CopyMagickString((char *) chunk+4,"CACHEOFF",20); (void) WriteBlobMSBULong(image,(size_t) length); LogPNGChunk(logging,mng_nEED,(size_t) length); length+=4; (void) WriteBlob(image,length,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write MNG TERM chunk */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_TERM); LogPNGChunk(logging,mng_TERM,10L); chunk[4]=3; /* repeat animation */ chunk[5]=0; /* show last frame when done */ PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) PNGLong(chunk+10,PNG_UINT_31_MAX); else PNGLong(chunk+10,(png_uint_32) image->iterations); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM delay: %.20g",(double) (mng_info->ticks_per_second* final_delay/MagickMax(image->ticks_per_second,1))); if (image->iterations == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " TERM iterations: %.20g",(double) PNG_UINT_31_MAX); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image iterations: %.20g",(double) image->iterations); } (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); } /* To do: check for cHRM+gAMA == sRGB, and write sRGB instead. */ if ((image->colorspace == sRGBColorspace || image->rendering_intent) && mng_info->equal_srgbs) { /* Write MNG sRGB chunk */ (void) WriteBlobMSBULong(image,1L); PNGType(chunk,mng_sRGB); LogPNGChunk(logging,mng_sRGB,1L); if (image->rendering_intent != UndefinedIntent) chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (image->rendering_intent)); else chunk[4]=(unsigned char) Magick_RenderingIntent_to_PNG_RenderingIntent( (PerceptualIntent)); (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); mng_info->have_write_global_srgb=MagickTrue; } else { if (image->gamma && mng_info->equal_gammas) { /* Write MNG gAMA chunk */ (void) WriteBlobMSBULong(image,4L); PNGType(chunk,mng_gAMA); LogPNGChunk(logging,mng_gAMA,4L); PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); (void) WriteBlob(image,8,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); mng_info->have_write_global_gama=MagickTrue; } if (mng_info->equal_chrms) { PrimaryInfo primary; /* Write MNG cHRM chunk */ (void) WriteBlobMSBULong(image,32L); PNGType(chunk,mng_cHRM); LogPNGChunk(logging,mng_cHRM,32L); primary=image->chromaticity.white_point; PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.red_primary; PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.green_primary; PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); primary=image->chromaticity.blue_primary; PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); (void) WriteBlob(image,36,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); mng_info->have_write_global_chrm=MagickTrue; } } if (image->x_resolution && image->y_resolution && mng_info->equal_physs) { /* Write MNG pHYs chunk */ (void) WriteBlobMSBULong(image,9L); PNGType(chunk,mng_pHYs); LogPNGChunk(logging,mng_pHYs,9L); if (image->units == PixelsPerInchResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0/2.54+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0/2.54+0.5)); chunk[12]=1; } else { if (image->units == PixelsPerCentimeterResolution) { PNGLong(chunk+4,(png_uint_32) (image->x_resolution*100.0+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution*100.0+0.5)); chunk[12]=1; } else { PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); chunk[12]=0; } } (void) WriteBlob(image,13,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); } /* Write MNG BACK chunk and global bKGD chunk, if the image is transparent or does not cover the entire frame. */ if (write_mng && (image->matte || image->page.x > 0 || image->page.y > 0 || (image->page.width && (image->page.width+image->page.x < mng_info->page.width)) || (image->page.height && (image->page.height+image->page.y < mng_info->page.height)))) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_BACK); LogPNGChunk(logging,mng_BACK,6L); red=ScaleQuantumToShort(image->background_color.red); green=ScaleQuantumToShort(image->background_color.green); blue=ScaleQuantumToShort(image->background_color.blue); PNGShort(chunk+4,red); PNGShort(chunk+6,green); PNGShort(chunk+8,blue); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); if (mng_info->equal_backgrounds) { (void) WriteBlobMSBULong(image,6L); PNGType(chunk,mng_bKGD); LogPNGChunk(logging,mng_bKGD,6L); (void) WriteBlob(image,10,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); } } #ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED if ((need_local_plte == MagickFalse) && (image->storage_class == PseudoClass) && (all_images_are_gray == MagickFalse)) { size_t data_length; /* Write MNG PLTE chunk */ data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } #endif } scene=0; mng_info->delay=0; #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) mng_info->equal_palettes=MagickFalse; #endif do { if (mng_info->adjoin) { #if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ defined(PNG_MNG_FEATURES_SUPPORTED) /* If we aren't using a global palette for the entire MNG, check to see if we can use one for two or more consecutive images. */ if (need_local_plte && use_global_plte && !all_images_are_gray) { if (mng_info->IsPalette) { /* When equal_palettes is true, this image has the same palette as the previous PseudoClass image */ mng_info->have_write_global_plte=mng_info->equal_palettes; mng_info->equal_palettes=PalettesAreEqual(image,image->next); if (mng_info->equal_palettes && !mng_info->have_write_global_plte) { /* Write MNG PLTE chunk */ size_t data_length; data_length=3*image->colors; (void) WriteBlobMSBULong(image,data_length); PNGType(chunk,mng_PLTE); LogPNGChunk(logging,mng_PLTE,data_length); for (i=0; i < (ssize_t) image->colors; i++) { chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); } (void) WriteBlob(image,data_length+4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk, (uInt) (data_length+4))); mng_info->have_write_global_plte=MagickTrue; } } else mng_info->have_write_global_plte=MagickFalse; } #endif if (need_defi) { ssize_t previous_x, previous_y; if (scene != 0) { previous_x=mng_info->page.x; previous_y=mng_info->page.y; } else { previous_x=0; previous_y=0; } mng_info->page=image->page; if ((mng_info->page.x != previous_x) || (mng_info->page.y != previous_y)) { (void) WriteBlobMSBULong(image,12L); /* data length=12 */ PNGType(chunk,mng_DEFI); LogPNGChunk(logging,mng_DEFI,12L); chunk[4]=0; /* object 0 MSB */ chunk[5]=0; /* object 0 LSB */ chunk[6]=0; /* visible */ chunk[7]=0; /* abstract */ PNGLong(chunk+8,(png_uint_32) mng_info->page.x); PNGLong(chunk+12,(png_uint_32) mng_info->page.y); (void) WriteBlob(image,16,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); } } } mng_info->write_mng=write_mng; if ((int) image->dispose >= 3) mng_info->framing_mode=3; if (mng_info->need_fram && mng_info->adjoin && ((image->delay != mng_info->delay) || (mng_info->framing_mode != mng_info->old_framing_mode))) { if (image->delay == mng_info->delay) { /* Write a MNG FRAM chunk with the new framing mode. */ (void) WriteBlobMSBULong(image,1L); /* data length=1 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,1L); chunk[4]=(unsigned char) mng_info->framing_mode; (void) WriteBlob(image,5,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); } else { /* Write a MNG FRAM chunk with the delay. */ (void) WriteBlobMSBULong(image,10L); /* data length=10 */ PNGType(chunk,mng_FRAM); LogPNGChunk(logging,mng_FRAM,10L); chunk[4]=(unsigned char) mng_info->framing_mode; chunk[5]=0; /* frame name separator (no name) */ chunk[6]=2; /* flag for changing default delay */ chunk[7]=0; /* flag for changing frame timeout */ chunk[8]=0; /* flag for changing frame clipping */ chunk[9]=0; /* flag for changing frame sync_id */ PNGLong(chunk+10,(png_uint_32) ((mng_info->ticks_per_second* image->delay)/MagickMax(image->ticks_per_second,1))); (void) WriteBlob(image,14,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); mng_info->delay=(png_uint_32) image->delay; } mng_info->old_framing_mode=mng_info->framing_mode; } #if defined(JNG_SUPPORTED) if (image_info->compression == JPEGCompression) { ImageInfo *write_info; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing JNG object."); /* To do: specify the desired alpha compression method. */ write_info=CloneImageInfo(image_info); write_info->compression=UndefinedCompression; status=WriteOneJNGImage(mng_info,write_info,image); write_info=DestroyImageInfo(write_info); } else #endif { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing PNG object."); mng_info->need_blob = MagickFalse; mng_info->ping_preserve_colormap = MagickFalse; /* We don't want any ancillary chunks written */ mng_info->ping_exclude_bKGD=MagickTrue; mng_info->ping_exclude_caNv=MagickTrue; mng_info->ping_exclude_cHRM=MagickTrue; mng_info->ping_exclude_date=MagickTrue; mng_info->ping_exclude_EXIF=MagickTrue; mng_info->ping_exclude_eXIf=MagickTrue; mng_info->ping_exclude_gAMA=MagickTrue; mng_info->ping_exclude_iCCP=MagickTrue; /* mng_info->ping_exclude_iTXt=MagickTrue; */ mng_info->ping_exclude_oFFs=MagickTrue; mng_info->ping_exclude_pHYs=MagickTrue; mng_info->ping_exclude_sRGB=MagickTrue; mng_info->ping_exclude_tEXt=MagickTrue; mng_info->ping_exclude_tRNS=MagickTrue; mng_info->ping_exclude_vpAg=MagickTrue; mng_info->ping_exclude_zCCP=MagickTrue; mng_info->ping_exclude_zTXt=MagickTrue; status=WriteOnePNGImage(mng_info,image_info,image); } if (status == MagickFalse) { mng_info=MngInfoFreeStruct(mng_info); (void) CloseBlob(image); return(MagickFalse); } (void) CatchImageException(image); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (mng_info->adjoin); if (write_mng) { while (GetPreviousImageInList(image) != (Image *) NULL) image=GetPreviousImageInList(image); /* Write the MEND chunk. */ (void) WriteBlobMSBULong(image,0x00000000L); PNGType(chunk,mng_MEND); LogPNGChunk(logging,mng_MEND,0L); (void) WriteBlob(image,4,chunk); (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); } /* Relinquish resources. */ (void) CloseBlob(image); mng_info=MngInfoFreeStruct(mng_info); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit WriteMNGImage()"); return(MagickTrue); } #else /* PNG_LIBPNG_VER > 10011 */ static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) { (void) image; printf("Your PNG library is too old: You have libpng-%s\n", PNG_LIBPNG_VER_STRING); ThrowBinaryException(CoderError,"PNG library is too old", image_info->filename); } static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) { return(WritePNGImage(image_info,image)); } #endif /* PNG_LIBPNG_VER > 10011 */ #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_2734_0
crossvul-cpp_data_good_351_8
/* * card-iasecc.c: Support for IAS/ECC smart cards * * Copyright (C) 2010 Viktor Tarasov <vtarasov@gmail.com> * OpenTrust <www.opentrust.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 */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <string.h> #include <stdlib.h> #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <openssl/rsa.h> #include <openssl/pkcs12.h> #include <openssl/x509v3.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" #include "opensc.h" /* #include "sm.h" */ #include "pkcs15.h" /* #include "hash-strings.h" */ #include "gp.h" #include "iasecc.h" #define IASECC_CARD_DEFAULT_FLAGS ( 0 \ | SC_ALGORITHM_ONBOARD_KEY_GEN \ | SC_ALGORITHM_RSA_PAD_ISO9796 \ | SC_ALGORITHM_RSA_PAD_PKCS1 \ | SC_ALGORITHM_RSA_HASH_NONE \ | SC_ALGORITHM_RSA_HASH_SHA1 \ | SC_ALGORITHM_RSA_HASH_SHA256) /* generic iso 7816 operations table */ static const struct sc_card_operations *iso_ops = NULL; /* our operations table with overrides */ static struct sc_card_operations iasecc_ops; static struct sc_card_driver iasecc_drv = { "IAS-ECC", "iasecc", &iasecc_ops, NULL, 0, NULL }; static struct sc_atr_table iasecc_known_atrs[] = { { "3B:7F:96:00:00:00:31:B8:64:40:70:14:10:73:94:01:80:82:90:00", "FF:FF:FF:FF:FF:FF:FF:FE:FF:FF:00:00:FF:FF:FF:FF:FF:FF:FF:FF", "IAS/ECC Gemalto", SC_CARD_TYPE_IASECC_GEMALTO, 0, NULL }, { "3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:08:00:07:90:00:FE", NULL, "IAS/ECC v1.0.1 Oberthur", SC_CARD_TYPE_IASECC_OBERTHUR, 0, NULL }, { "3B:7D:13:00:00:4D:44:57:2D:49:41:53:2D:43:41:52:44:32", NULL, "IAS/ECC v1.0.1 Sagem MDW-IAS-CARD2", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL }, { "3B:7F:18:00:00:00:31:B8:64:50:23:EC:C1:73:94:01:80:82:90:00", NULL, "IAS/ECC v1.0.1 Sagem ypsID S3", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL }, { "3B:DF:96:00:80:31:FE:45:00:31:B8:64:04:1F:EC:C1:73:94:01:80:82:90:00:EC", NULL, "IAS/ECC Morpho MinInt - Agent Card", SC_CARD_TYPE_IASECC_MI, 0, NULL }, { "3B:DF:18:FF:81:91:FE:1F:C3:00:31:B8:64:0C:01:EC:C1:73:94:01:80:82:90:00:B3", NULL, "IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL }, { "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:02:04:03:55:00:02:34", NULL, "IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL }, { "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:01:0B:03:52:00:05:38", NULL, "IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_aid OberthurIASECC_AID = { {0xA0,0x00,0x00,0x00,0x77,0x01,0x08,0x00,0x07,0x00,0x00,0xFE,0x00,0x00,0x01,0x00}, 16 }; static struct sc_aid MIIASECC_AID = { { 0x4D, 0x49, 0x4F, 0x4D, 0x43, 0x54}, 6 }; struct iasecc_pin_status { unsigned char sha1[SHA_DIGEST_LENGTH]; unsigned char reference; struct iasecc_pin_status *next; struct iasecc_pin_status *prev; }; struct iasecc_pin_status *checked_pins = NULL; static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out); static int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen); static int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial); static int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo); static int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data); static int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left); static int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data); static int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update); #ifdef ENABLE_SM static int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count); static int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count); #endif static int iasecc_chv_cache_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct iasecc_pin_status *pin_status = NULL, *current = NULL; LOG_FUNC_CALLED(ctx); for(current = checked_pins; current; current = current->next) if (current->reference == pin_cmd->pin_reference) break; if (current) { sc_log(ctx, "iasecc_chv_cache_verified() current PIN-%i", current->reference); pin_status = current; } else { pin_status = calloc(1, sizeof(struct iasecc_pin_status)); if (!pin_status) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate PIN status info"); sc_log(ctx, "iasecc_chv_cache_verified() allocated %p", pin_status); } pin_status->reference = pin_cmd->pin_reference; if (pin_cmd->pin1.data) SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_status->sha1); else memset(pin_status->sha1, 0, SHA_DIGEST_LENGTH); sc_log_hex(ctx, "iasecc_chv_cache_verified() sha1(PIN)", pin_status->sha1, SHA_DIGEST_LENGTH); if (!current) { if (!checked_pins) { checked_pins = pin_status; } else { checked_pins->prev = pin_status; pin_status->next = checked_pins; checked_pins = pin_status; } } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_chv_cache_clean(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct iasecc_pin_status *current = NULL; LOG_FUNC_CALLED(ctx); for(current = checked_pins; current; current = current->next) if (current->reference == pin_cmd->pin_reference) break; if (!current) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (current->next && current->prev) { current->prev->next = current->next; current->next->prev = current->prev; } else if (!current->prev) { checked_pins = current->next; } else if (!current->next && current->prev) { current->prev->next = NULL; } free(current); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static struct iasecc_pin_status * iasecc_chv_cache_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct iasecc_pin_status *current = NULL; unsigned char data_sha1[SHA_DIGEST_LENGTH]; LOG_FUNC_CALLED(ctx); if (pin_cmd->pin1.data) SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, data_sha1); else memset(data_sha1, 0, SHA_DIGEST_LENGTH); sc_log_hex(ctx, "data_sha1: %s", data_sha1, SHA_DIGEST_LENGTH); for(current = checked_pins; current; current = current->next) if (current->reference == pin_cmd->pin_reference) break; if (current && !memcmp(data_sha1, current->sha1, SHA_DIGEST_LENGTH)) { sc_log(ctx, "PIN-%i status 'verified'", pin_cmd->pin_reference); return current; } sc_log(ctx, "PIN-%i status 'not verified'", pin_cmd->pin_reference); return NULL; } static int iasecc_select_mf(struct sc_card *card, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *mf_file = NULL; struct sc_path path; int rv; LOG_FUNC_CALLED(ctx); if (file_out) *file_out = NULL; memset(&path, 0, sizeof(struct sc_path)); if (!card->ef_atr || !card->ef_atr->aid.len) { struct sc_apdu apdu; unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE]; /* ISO 'select' command fails when not FCP data returned */ sc_format_path("3F00", &path); path.type = SC_PATH_TYPE_FILE_ID; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00); apdu.lc = path.len; apdu.data = path.value; apdu.datalen = path.len; apdu.resplen = sizeof(apdu_resp); apdu.resp = apdu_resp; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, rv, "Cannot select MF"); } else { memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, file_out); LOG_TEST_RET(ctx, rv, "Unable to ROOT selection"); } /* Ignore the FCP of the MF, because: * - some cards do not return it; * - there is not need of it -- create/delete of the files in MF is not envisaged. */ mf_file = sc_file_new(); if (mf_file == NULL) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate MF file"); mf_file->type = SC_FILE_TYPE_DF; mf_file->path = path; if (card->cache.valid) sc_file_free(card->cache.current_df); card->cache.current_df = NULL; if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_df, mf_file); card->cache.valid = 1; if (file_out && *file_out == NULL) *file_out = mf_file; else sc_file_free(mf_file); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_select_aid(struct sc_card *card, struct sc_aid *aid, unsigned char *out, size_t *out_len) { struct sc_apdu apdu; unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE]; int rv; /* Select application (deselect previously selected application) */ sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00); apdu.lc = aid->len; apdu.data = aid->value; apdu.datalen = aid->len; apdu.resplen = sizeof(apdu_resp); apdu.resp = apdu_resp; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, rv, "Cannot select AID"); if (*out_len < apdu.resplen) LOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, "Cannot select AID"); memcpy(out, apdu.resp, apdu.resplen); return SC_SUCCESS; } static int iasecc_match_card(struct sc_card *card) { struct sc_context *ctx = card->ctx; int i; i = _sc_match_atr(card, iasecc_known_atrs, &card->type); if (i < 0) { sc_log(ctx, "card not matched"); return 0; } sc_log(ctx, "'%s' card matched", iasecc_known_atrs[i].name); return 1; } static int iasecc_parse_ef_atr(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *pdata = (struct iasecc_private_data *) card->drv_data; struct iasecc_version *version = &pdata->version; struct iasecc_io_buffer_sizes *sizes = &pdata->max_sizes; int rv; LOG_FUNC_CALLED(ctx); rv = sc_parse_ef_atr(card); LOG_TEST_RET(ctx, rv, "MF selection error"); if (card->ef_atr->pre_issuing_len < 4) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid pre-issuing data"); version->ic_manufacturer = card->ef_atr->pre_issuing[0]; version->ic_type = card->ef_atr->pre_issuing[1]; version->os_version = card->ef_atr->pre_issuing[2]; version->iasecc_version = card->ef_atr->pre_issuing[3]; sc_log(ctx, "EF.ATR: IC manufacturer/type %X/%X, OS/IasEcc versions %X/%X", version->ic_manufacturer, version->ic_type, version->os_version, version->iasecc_version); if (card->ef_atr->issuer_data_len < 16) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid issuer data"); sizes->send = card->ef_atr->issuer_data[2] * 0x100 + card->ef_atr->issuer_data[3]; sizes->send_sc = card->ef_atr->issuer_data[6] * 0x100 + card->ef_atr->issuer_data[7]; sizes->recv = card->ef_atr->issuer_data[10] * 0x100 + card->ef_atr->issuer_data[11]; sizes->recv_sc = card->ef_atr->issuer_data[14] * 0x100 + card->ef_atr->issuer_data[15]; card->max_send_size = sizes->send; card->max_recv_size = sizes->recv; /* Most of the card producers interpret 'send' values as "maximum APDU data size". * Oberthur strictly follows specification and interpret these values as "maximum APDU command size". * Here we need 'data size'. */ if (card->max_send_size > 0xFF) card->max_send_size -= 5; sc_log(ctx, "EF.ATR: max send/recv sizes %"SC_FORMAT_LEN_SIZE_T"X/%"SC_FORMAT_LEN_SIZE_T"X", card->max_send_size, card->max_recv_size); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init_gemalto(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct sc_path path; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = IASECC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; sc_format_path("3F00", &path); rv = sc_select_file(card, &path, NULL); /* Result ignored*/ rv = iasecc_parse_ef_atr(card); sc_log(ctx, "rv %i", rv); if (rv == SC_ERROR_FILE_NOT_FOUND) { sc_log(ctx, "Select MF"); rv = iasecc_select_mf(card, NULL); sc_log(ctx, "rv %i", rv); LOG_TEST_RET(ctx, rv, "MF selection error"); rv = iasecc_parse_ef_atr(card); sc_log(ctx, "rv %i", rv); } sc_log(ctx, "rv %i", rv); LOG_TEST_RET(ctx, rv, "Cannot read/parse EF.ATR"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_oberthur_match(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned char *hist = card->reader->atr_info.hist_bytes; LOG_FUNC_CALLED(ctx); if (*hist != 0x80 || ((*(hist+1)&0xF0) != 0xF0)) LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND); sc_log_hex(ctx, "AID in historical_bytes", hist + 2, *(hist+1) & 0x0F); if (memcmp(hist + 2, OberthurIASECC_AID.value, *(hist+1) & 0x0F)) LOG_FUNC_RETURN(ctx, SC_ERROR_RECORD_NOT_FOUND); if (!card->ef_atr) card->ef_atr = calloc(1, sizeof(struct sc_ef_atr)); if (!card->ef_atr) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(card->ef_atr->aid.value, OberthurIASECC_AID.value, OberthurIASECC_AID.len); card->ef_atr->aid.len = OberthurIASECC_AID.len; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init_oberthur(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = IASECC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; iasecc_parse_ef_atr(card); /* if we fail to select CM, */ if (gp_select_card_manager(card)) { gp_select_isd_rid(card); } rv = iasecc_oberthur_match(card); LOG_TEST_RET(ctx, rv, "unknown Oberthur's IAS/ECC card"); rv = iasecc_select_mf(card, NULL); LOG_TEST_RET(ctx, rv, "MF selection error"); rv = iasecc_parse_ef_atr(card); LOG_TEST_RET(ctx, rv, "EF.ATR read or parse error"); sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len)); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_mi_match(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned char resp[0x100]; size_t resp_len; int rv = 0; LOG_FUNC_CALLED(ctx); resp_len = sizeof(resp); rv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len); LOG_TEST_RET(ctx, rv, "IASECC: failed to select MI IAS/ECC applet"); if (!card->ef_atr) card->ef_atr = calloc(1, sizeof(struct sc_ef_atr)); if (!card->ef_atr) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len); card->ef_atr->aid.len = MIIASECC_AID.len; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init_amos_or_sagem(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = IASECC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; if (card->type == SC_CARD_TYPE_IASECC_MI) { rv = iasecc_mi_match(card); if (rv) card->type = SC_CARD_TYPE_IASECC_MI2; else LOG_FUNC_RETURN(ctx, SC_SUCCESS); } rv = iasecc_parse_ef_atr(card); if (rv == SC_ERROR_FILE_NOT_FOUND) { rv = iasecc_select_mf(card, NULL); LOG_TEST_RET(ctx, rv, "MF selection error"); rv = iasecc_parse_ef_atr(card); } LOG_TEST_RET(ctx, rv, "IASECC: ATR parse failed"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *private_data = NULL; int rv = SC_ERROR_NO_CARD_SUPPORT; LOG_FUNC_CALLED(ctx); private_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data)); if (private_data == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); card->cla = 0x00; card->drv_data = private_data; if (card->type == SC_CARD_TYPE_IASECC_GEMALTO) rv = iasecc_init_gemalto(card); else if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) rv = iasecc_init_oberthur(card); else if (card->type == SC_CARD_TYPE_IASECC_SAGEM) rv = iasecc_init_amos_or_sagem(card); else if (card->type == SC_CARD_TYPE_IASECC_AMOS) rv = iasecc_init_amos_or_sagem(card); else if (card->type == SC_CARD_TYPE_IASECC_MI) rv = iasecc_init_amos_or_sagem(card); else LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD); if (!rv) { if (card->ef_atr && card->ef_atr->aid.len) { struct sc_path path; memset(&path, 0, sizeof(struct sc_path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, NULL); sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv); LOG_TEST_RET(ctx, rv, "Select EF.ATR AID failed"); } rv = iasecc_get_serialnr(card, NULL); } #ifdef ENABLE_SM card->sm_ctx.ops.read_binary = _iasecc_sm_read_binary; card->sm_ctx.ops.update_binary = _iasecc_sm_update_binary; #endif if (!rv) { sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len)); rv = SC_ERROR_INVALID_CARD; } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_read_binary(card:%p) offs %i; count %"SC_FORMAT_LEN_SIZE_T"u", card, offs, count); if (offs > 0x7fff) { sc_log(ctx, "invalid EF offset: 0x%X > 0x7FFF", offs); return SC_ERROR_OFFSET_TOO_LARGE; } sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (offs >> 8) & 0x7F, offs & 0xFF); apdu.le = count < 0x100 ? count : 0x100; apdu.resplen = count; apdu.resp = buf; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "iasecc_read_binary() failed"); sc_log(ctx, "iasecc_read_binary() apdu.resplen %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen == IASECC_READ_BINARY_LENGTH_MAX && apdu.resplen < count) { rv = iasecc_read_binary(card, offs + apdu.resplen, buf + apdu.resplen, count - apdu.resplen, flags); if (rv != SC_ERROR_WRONG_LENGTH) { LOG_TEST_RET(ctx, rv, "iasecc_read_binary() read tail failed"); apdu.resplen += rv; } } LOG_FUNC_RETURN(ctx, apdu.resplen); } static int iasecc_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; unsigned char *tmp = NULL; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_erase_binary(card:%p) count %"SC_FORMAT_LEN_SIZE_T"u", card, count); if (!count) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "'ERASE BINARY' failed: invalid size to erase"); tmp = malloc(count); if (!tmp) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate temporary buffer"); memset(tmp, 0xFF, count); rv = sc_update_binary(card, offs, tmp, count, flags); free(tmp); LOG_TEST_RET(ctx, rv, "iasecc_erase_binary() update binary error"); LOG_FUNC_RETURN(ctx, rv); } #if ENABLE_SM static int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buff, size_t count) { struct sc_context *ctx = card->ctx; const struct sc_acl_entry *entry = NULL; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ", card, offs, count); if (offs > 0x7fff) LOG_TEST_RET(ctx, SC_ERROR_OFFSET_TOO_LARGE, "Invalid arguments"); if (count == 0) return 0; sc_print_cache(card); if (card->cache.valid && card->cache.current_ef) { entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_READ); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_read() 'READ' ACL not present"); sc_log(ctx, "READ method/reference %X/%X", entry->method, entry->key_ref); if ((entry->method == SC_AC_SCB) && (entry->key_ref & IASECC_SCB_METHOD_SM)) { unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0; rv = iasecc_sm_read_binary(card, se_num, offs, buff, count); LOG_FUNC_RETURN(ctx, rv); } } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count) { struct sc_context *ctx = card->ctx; const struct sc_acl_entry *entry = NULL; int rv; if (count == 0) return SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ", card, offs, count); sc_print_cache(card); if (card->cache.valid && card->cache.current_ef) { entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_UPDATE); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_update() 'UPDATE' ACL not present"); sc_log(ctx, "UPDATE method/reference %X/%X", entry->method, entry->key_ref); if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) { unsigned char se_num = entry->method == SC_AC_SCB ? entry->key_ref & IASECC_SCB_METHOD_MASK_REF : 0; rv = iasecc_sm_update_binary(card, se_num, offs, buff, count); LOG_FUNC_RETURN(ctx, rv); } } LOG_FUNC_RETURN(ctx, 0); } #endif static int iasecc_emulate_fcp(struct sc_context *ctx, struct sc_apdu *apdu) { unsigned char dummy_df_fcp[] = { 0x62,0xFF, 0x82,0x01,0x38, 0x8A,0x01,0x05, 0xA1,0x04,0x8C,0x02,0x02,0x00, 0x84,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF }; LOG_FUNC_CALLED(ctx); if (apdu->p1 != 0x04) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "FCP emulation supported only for the DF-NAME selection type"); if (apdu->datalen > 16) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid DF-NAME length"); if (apdu->resplen < apdu->datalen + 16) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "not enough space for FCP data"); memcpy(dummy_df_fcp + 16, apdu->data, apdu->datalen); dummy_df_fcp[15] = apdu->datalen; dummy_df_fcp[1] = apdu->datalen + 14; memcpy(apdu->resp, dummy_df_fcp, apdu->datalen + 16); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } /* TODO: redesign using of cache * TODO: do not keep intermediate results in 'file_out' argument */ static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_path lpath; int cache_valid = card->cache.valid, df_from_cache = 0; int rv, ii; LOG_FUNC_CALLED(ctx); memcpy(&lpath, path, sizeof(struct sc_path)); if (file_out) *file_out = NULL; sc_log(ctx, "iasecc_select_file(card:%p) path.len %"SC_FORMAT_LEN_SIZE_T"u; path.type %i; aid_len %"SC_FORMAT_LEN_SIZE_T"u", card, path->len, path->type, path->aid.len); sc_log(ctx, "iasecc_select_file() path:%s", sc_print_path(path)); sc_print_cache(card); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { sc_log(ctx, "EF.ATR(aid:'%s')", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : ""); rv = iasecc_select_mf(card, file_out); LOG_TEST_RET(ctx, rv, "MF selection error"); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2); lpath.len -= 2; } } if (lpath.aid.len) { struct sc_file *file = NULL; struct sc_path ppath; sc_log(ctx, "iasecc_select_file() select parent AID:%p/%"SC_FORMAT_LEN_SIZE_T"u", lpath.aid.value, lpath.aid.len); sc_log(ctx, "iasecc_select_file() select parent AID:%s", sc_dump_hex(lpath.aid.value, lpath.aid.len)); memset(&ppath, 0, sizeof(ppath)); memcpy(ppath.value, lpath.aid.value, lpath.aid.len); ppath.len = lpath.aid.len; ppath.type = SC_PATH_TYPE_DF_NAME; if (card->cache.valid && card->cache.current_df && card->cache.current_df->path.len == lpath.aid.len && !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len)) df_from_cache = 1; rv = iasecc_select_file(card, &ppath, &file); LOG_TEST_RET(ctx, rv, "select AID path failed"); if (file_out) *file_out = file; else sc_file_free(file); if (lpath.type == SC_PATH_TYPE_DF_NAME) lpath.type = SC_PATH_TYPE_FROM_CURRENT; } if (lpath.type == SC_PATH_TYPE_PATH) lpath.type = SC_PATH_TYPE_FROM_CURRENT; if (!lpath.len) LOG_FUNC_RETURN(ctx, SC_SUCCESS); sc_print_cache(card); if (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME && card->cache.current_df->path.len == lpath.len && !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) { sc_log(ctx, "returns current DF path %s", sc_print_path(&card->cache.current_df->path)); if (file_out) { sc_file_free(*file_out); sc_file_dup(file_out, card->cache.current_df); } sc_print_cache(card); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } do { struct sc_apdu apdu; struct sc_file *file = NULL; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int pathlen = lpath.len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); if (card->type != SC_CARD_TYPE_IASECC_GEMALTO && card->type != SC_CARD_TYPE_IASECC_OBERTHUR && card->type != SC_CARD_TYPE_IASECC_SAGEM && card->type != SC_CARD_TYPE_IASECC_AMOS && card->type != SC_CARD_TYPE_IASECC_MI && card->type != SC_CARD_TYPE_IASECC_MI2) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card"); if (lpath.type == SC_PATH_TYPE_FILE_ID) { apdu.p1 = 0x02; if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) { apdu.p1 = 0x01; apdu.p2 = 0x04; } if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) { apdu.p1 = 0x09; if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else if (lpath.type == SC_PATH_TYPE_PARENT) { apdu.p1 = 0x03; pathlen = 0; apdu.cse = SC_APDU_CASE_2_SHORT; } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { apdu.p1 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else { sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type); LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "iasecc_select_file() invalid PATH type"); } for (ii=0; ii<2; ii++) { apdu.lc = pathlen; apdu.data = lpath.value; apdu.datalen = pathlen; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (rv == SC_ERROR_INCORRECT_PARAMETERS && lpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) { apdu.p2 = 0x0C; continue; } if (ii) { /* 'SELECT AID' do not returned FCP. Try to emulate. */ apdu.resplen = sizeof(rbuf); rv = iasecc_emulate_fcp(ctx, &apdu); LOG_TEST_RET(ctx, rv, "Failed to emulate DF FCP"); } break; } /* * Using of the cached DF and EF can cause problems in the multi-thread environment. * FIXME: introduce config. option that invalidates this cache outside the locked card session, * (or invent something else) */ if (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) { sc_invalidate_cache(card); sc_log(ctx, "iasecc_select_file() file not found, retry without cached DF"); if (file_out) { sc_file_free(*file_out); *file_out = NULL; } rv = iasecc_select_file(card, path, file_out); LOG_FUNC_RETURN(ctx, rv); } LOG_TEST_RET(ctx, rv, "iasecc_select_file() check SW failed"); sc_log(ctx, "iasecc_select_file() apdu.resp %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen) { sc_log(ctx, "apdu.resp %02X:%02X:%02X...", apdu.resp[0], apdu.resp[1], apdu.resp[2]); switch (apdu.resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = lpath; rv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen); if (rv) LOG_FUNC_RETURN(ctx, rv); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } sc_log(ctx, "FileType %i", file->type); if (file->type == SC_FILE_TYPE_DF) { if (card->cache.valid) sc_file_free(card->cache.current_df); card->cache.current_df = NULL; if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_df, file); card->cache.valid = 1; } else { if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) { sc_file_free(*file_out); *file_out = file; } else { sc_file_free(file); } } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { sc_file_free(card->cache.current_df); card->cache.current_df = NULL; sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } } while(0); sc_print_cache(card); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv, ii, offs; const unsigned char *acls = NULL, *tag = NULL; unsigned char mask; unsigned char ops_DF[7] = { SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_CREATE, 0xFF }; unsigned char ops_EF[7] = { SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(ctx, buf, buflen, 0x6F, &taglen); sc_log(ctx, "processing FCI: 0x6F tag %p", tag); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(ctx, buf, buflen, 0x62, &taglen); sc_log(ctx, "processing FCI: 0x62 tag %p", tag); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); /* Gemalto: 6F 19 80 02 02 ED 82 01 01 83 02 B0 01 88 00 8C 07 7B 17 17 17 17 17 00 8A 01 05 90 00 Sagem: 6F 17 62 15 80 02 00 7D 82 01 01 8C 02 01 00 83 02 2F 00 88 01 F0 8A 01 05 90 00 Oberthur: 62 1B 80 02 05 DC 82 01 01 83 02 B0 01 88 00 A1 09 8C 07 7B 17 FF 17 17 17 00 8A 01 05 90 00 */ sc_log(ctx, "iasecc_process_fci() type %i; let's parse file ACLs", file->type); tag = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS, &taglen); if (tag) acls = sc_asn1_find_tag(ctx, tag, taglen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen); else acls = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen); if (!acls) { sc_log(ctx, "ACLs not found in data(%"SC_FORMAT_LEN_SIZE_T"u) %s", buflen, sc_dump_hex(buf, buflen)); LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } sc_log(ctx, "ACLs(%"SC_FORMAT_LEN_SIZE_T"u) '%s'", taglen, sc_dump_hex(acls, taglen)); mask = 0x40, offs = 1; for (ii = 0; ii < 7; ii++, mask /= 2) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; if (!(mask & acls[0])) continue; sc_log(ctx, "ACLs mask 0x%X, offs %i, op 0x%X, acls[offs] 0x%X", mask, offs, op, acls[offs]); if (op == 0xFF) { ; } else if (acls[offs] == 0) { sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); } else if (acls[offs] == 0xFF) { sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } else if ((acls[offs] & IASECC_SCB_METHOD_MASK) == IASECC_SCB_METHOD_USER_AUTH) { sc_file_add_acl_entry(file, op, SC_AC_SEN, acls[offs] & IASECC_SCB_METHOD_MASK_REF); } else if (acls[offs] & IASECC_SCB_METHOD_MASK) { sc_file_add_acl_entry(file, op, SC_AC_SCB, acls[offs]); } else { sc_log(ctx, "Warning: non supported SCB method: %X", acls[offs]); sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } offs++; } LOG_FUNC_RETURN(ctx, 0); } static int iasecc_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; unsigned char buf[0x80], type; unsigned char ops[7] = { SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ }; unsigned char smbs[8]; size_t ii, offs = 0, amb, mask, nn_smb; LOG_FUNC_CALLED(ctx); if (file->type == SC_FILE_TYPE_DF) type = IASECC_FCP_TYPE_DF; else type = IASECC_FCP_TYPE_EF; buf[offs++] = IASECC_FCP_TAG_SIZE; buf[offs++] = 2; buf[offs++] = (file->size >> 8) & 0xFF; buf[offs++] = file->size & 0xFF; buf[offs++] = IASECC_FCP_TAG_TYPE; buf[offs++] = 1; buf[offs++] = type; buf[offs++] = IASECC_FCP_TAG_FID; buf[offs++] = 2; buf[offs++] = (file->id >> 8) & 0xFF; buf[offs++] = file->id & 0xFF; buf[offs++] = IASECC_FCP_TAG_SFID; buf[offs++] = 0; amb = 0, mask = 0x40, nn_smb = 0; for (ii = 0; ii < sizeof(ops); ii++, mask >>= 1) { const struct sc_acl_entry *entry; if (ops[ii]==0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); if (!entry) continue; sc_log(ctx, "method %X; reference %X", entry->method, entry->key_ref); if (entry->method == SC_AC_NEVER) continue; else if (entry->method == SC_AC_NONE) smbs[nn_smb++] = 0x00; else if (entry->method == SC_AC_CHV) smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH; else if (entry->method == SC_AC_SEN) smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH; else if (entry->method == SC_AC_SCB) smbs[nn_smb++] = entry->key_ref; else if (entry->method == SC_AC_PRO) smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_SM; else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported AC method"); amb |= mask; sc_log(ctx, "%"SC_FORMAT_LEN_SIZE_T"u: AMB %"SC_FORMAT_LEN_SIZE_T"X; nn_smb %"SC_FORMAT_LEN_SIZE_T"u", ii, amb, nn_smb); } /* TODO: Encode contactless ACLs and life cycle status for all IAS/ECC cards */ if (card->type == SC_CARD_TYPE_IASECC_SAGEM || card->type == SC_CARD_TYPE_IASECC_AMOS ) { unsigned char status = 0; buf[offs++] = IASECC_FCP_TAG_ACLS; buf[offs++] = 2*(2 + 1 + nn_smb); buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT; buf[offs++] = nn_smb + 1; buf[offs++] = amb; memcpy(buf + offs, smbs, nn_smb); offs += nn_smb; /* Same ACLs for contactless */ buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACTLESS; buf[offs++] = nn_smb + 1; buf[offs++] = amb; memcpy(buf + offs, smbs, nn_smb); offs += nn_smb; if (file->status == SC_FILE_STATUS_ACTIVATED) status = 0x05; else if (file->status == SC_FILE_STATUS_CREATION) status = 0x01; if (status) { buf[offs++] = 0x8A; buf[offs++] = 0x01; buf[offs++] = status; } } else { buf[offs++] = IASECC_FCP_TAG_ACLS; buf[offs++] = 2 + 1 + nn_smb; buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT; buf[offs++] = nn_smb + 1; buf[offs++] = amb; memcpy(buf + offs, smbs, nn_smb); offs += nn_smb; } if (out) { if (out_len < offs) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to encode FCP"); memcpy(out, buf, offs); } LOG_FUNC_RETURN(ctx, offs); } static int iasecc_create_file(struct sc_card *card, struct sc_file *file) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; const struct sc_acl_entry *entry = NULL; unsigned char sbuf[0x100]; size_t sbuf_len; int rv; LOG_FUNC_CALLED(ctx); sc_print_cache(card); if (file->type != SC_FILE_TYPE_WORKING_EF) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Creation of the file with of this type is not supported"); sbuf_len = iasecc_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2); LOG_TEST_RET(ctx, sbuf_len, "FCP encode error"); sbuf[0] = IASECC_FCP_TAG; sbuf[1] = sbuf_len; if (card->cache.valid && card->cache.current_df) { entry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_create_file() 'CREATE' ACL not present"); sc_log(ctx, "iasecc_create_file() 'CREATE' method/reference %X/%X", entry->method, entry->key_ref); sc_log(ctx, "iasecc_create_file() create data: '%s'", sc_dump_hex(sbuf, sbuf_len + 2)); if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) { rv = iasecc_sm_create_file(card, entry->key_ref & IASECC_SCB_METHOD_MASK_REF, sbuf, sbuf_len + 2); LOG_TEST_RET(ctx, rv, "iasecc_create_file() SM create file error"); rv = iasecc_select_file(card, &file->path, NULL); LOG_FUNC_RETURN(ctx, rv); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0); apdu.data = sbuf; apdu.datalen = sbuf_len + 2; apdu.lc = sbuf_len + 2; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "iasecc_create_file() create file error"); rv = iasecc_select_file(card, &file->path, NULL); LOG_TEST_RET(ctx, rv, "Cannot select newly created file"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_logout(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct sc_path path; int rv; LOG_FUNC_CALLED(ctx); if (!card->ef_atr || !card->ef_atr->aid.len) return SC_SUCCESS; memset(&path, 0, sizeof(struct sc_path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, NULL); sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_finish(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *private_data = (struct iasecc_private_data *)card->drv_data; struct iasecc_se_info *se_info = private_data->se_info, *next; LOG_FUNC_CALLED(ctx); while (se_info) { sc_file_free(se_info->df); next = se_info->next; free(se_info); se_info = next; } free(card->drv_data); card->drv_data = NULL; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_delete_file(struct sc_card *card, const struct sc_path *path) { struct sc_context *ctx = card->ctx; const struct sc_acl_entry *entry = NULL; struct sc_apdu apdu; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); sc_print_cache(card); rv = iasecc_select_file(card, path, &file); if (rv == SC_ERROR_FILE_NOT_FOUND) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_TEST_RET(ctx, rv, "Cannot select file to delete"); entry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot delete file: no 'DELETE' acl"); sc_log(ctx, "DELETE method/reference %X/%X", entry->method, entry->key_ref); if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) { unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0; rv = iasecc_sm_delete_file(card, se_num, file->id); } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xE4, 0x00, 0x00); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Delete file failed"); if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; } sc_file_free(file); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { if (sw1 == 0x62 && sw2 == 0x82) return SC_SUCCESS; return iso_ops->check_sw(card, sw1, sw2); } static unsigned iasecc_get_algorithm(struct sc_context *ctx, const struct sc_security_env *env, unsigned operation, unsigned mechanism) { const struct sc_supported_algo_info *info = NULL; int ii; if (!env) return 0; for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference; ii++) if ((env->supported_algos[ii].operations & operation) && (env->supported_algos[ii].mechanism == mechanism)) break; if (ii < SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference) { info = &env->supported_algos[ii]; sc_log(ctx, "found IAS/ECC algorithm %X:%X:%X:%X", info->reference, info->mechanism, info->operations, info->algo_ref); } else { sc_log(ctx, "cannot find IAS/ECC algorithm (operation:%X,mechanism:%X)", operation, mechanism); } return info ? info->algo_ref : 0; } static int iasecc_se_cache_info(struct sc_card *card, struct iasecc_se_info *se) { struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_context *ctx = card->ctx; struct iasecc_se_info *se_info = NULL, *si = NULL; int rv; LOG_FUNC_CALLED(ctx); se_info = calloc(1, sizeof(struct iasecc_se_info)); if (!se_info) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "SE info allocation error"); memcpy(se_info, se, sizeof(struct iasecc_se_info)); if (card->cache.valid && card->cache.current_df) { sc_file_dup(&se_info->df, card->cache.current_df); if (se_info->df == NULL) { free(se_info); LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file"); } } rv = iasecc_docp_copy(ctx, &se->docp, &se_info->docp); if (rv < 0) { free(se_info->df); free(se_info); LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP"); } if (!prv->se_info) { prv->se_info = se_info; } else { for (si = prv->se_info; si->next; si = si->next) ; si->next = se_info; } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_se_get_info_from_cache(struct sc_card *card, struct iasecc_se_info *se) { struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_context *ctx = card->ctx; struct iasecc_se_info *si = NULL; int rv; LOG_FUNC_CALLED(ctx); for(si = prv->se_info; si; si = si->next) { if (si->reference != se->reference) continue; if (!(card->cache.valid && card->cache.current_df) && si->df) continue; if (card->cache.valid && card->cache.current_df && !si->df) continue; if (card->cache.valid && card->cache.current_df && si->df) if (memcmp(&card->cache.current_df->path, &si->df->path, sizeof(struct sc_path))) continue; break; } if (!si) return SC_ERROR_OBJECT_NOT_FOUND; memcpy(se, si, sizeof(struct iasecc_se_info)); if (si->df) { sc_file_dup(&se->df, si->df); if (se->df == NULL) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file"); } rv = iasecc_docp_copy(ctx, &si->docp, &se->docp); LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP"); LOG_FUNC_RETURN(ctx, rv); } int iasecc_se_get_info(struct sc_card *card, struct iasecc_se_info *se) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char rbuf[0x100]; unsigned char sbuf_iasecc[10] = { 0x4D, 0x08, IASECC_SDO_TEMPLATE_TAG, 0x06, IASECC_SDO_TAG_HEADER, IASECC_SDO_CLASS_SE | IASECC_OBJECT_REF_LOCAL, se->reference & 0x3F, 0x02, IASECC_SDO_CLASS_SE, 0x80 }; int rv; LOG_FUNC_CALLED(ctx); if (se->reference > IASECC_SE_REF_MAX) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); rv = iasecc_se_get_info_from_cache(card, se); if (rv == SC_ERROR_OBJECT_NOT_FOUND) { sc_log(ctx, "No SE#%X info in cache, try to use 'GET DATA'", se->reference); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF); apdu.data = sbuf_iasecc; apdu.datalen = sizeof(sbuf_iasecc); apdu.lc = apdu.datalen; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "get SE data error"); rv = iasecc_se_parse(card, apdu.resp, apdu.resplen, se); LOG_TEST_RET(ctx, rv, "cannot parse SE data"); rv = iasecc_se_cache_info(card, se); LOG_TEST_RET(ctx, rv, "failed to put SE data into cache"); } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_set_security_env(struct sc_card *card, const struct sc_security_env *env, int se_num) { struct sc_context *ctx = card->ctx; struct iasecc_sdo sdo; struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; unsigned algo_ref; struct sc_apdu apdu; unsigned sign_meth, sign_ref, auth_meth, auth_ref, aflags; unsigned char cse_crt_at[] = { 0x84, 0x01, 0xFF, 0x80, 0x01, IASECC_ALGORITHM_RSA_PKCS }; unsigned char cse_crt_dst[] = { 0x84, 0x01, 0xFF, 0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1) }; unsigned char cse_crt_ht[] = { 0x80, 0x01, IASECC_ALGORITHM_SHA1 }; unsigned char cse_crt_ct[] = { 0x84, 0x01, 0xFF, 0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1) }; int rv, operation = env->operation; /* TODO: take algorithm references from 5032, not from header file. */ LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_set_security_env(card:%p) operation 0x%X; senv.algorithm 0x%X, senv.algorithm_ref 0x%X", card, env->operation, env->algorithm, env->algorithm_ref); memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_RSA_PRIVATE; sdo.sdo_ref = env->key_ref[0] & ~IASECC_OBJECT_REF_LOCAL; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "Cannot get RSA PRIVATE SDO data"); /* To made by iasecc_sdo_convert_to_file() */ prv->key_size = *(sdo.docp.size.value + 0) * 0x100 + *(sdo.docp.size.value + 1); sc_log(ctx, "prv->key_size 0x%"SC_FORMAT_LEN_SIZE_T"X", prv->key_size); rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_COMPUTE_SIGNATURE, &sign_meth, &sign_ref); LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_SIGN acl"); rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_INTERNAL_AUTHENTICATE, &auth_meth, &auth_ref); LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_INT_AUTH acl"); aflags = env->algorithm_flags; if (!(aflags & SC_ALGORITHM_RSA_PAD_PKCS1)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only supported signature with PKCS1 padding"); if (operation == SC_SEC_OPERATION_SIGN) { if (!(aflags & (SC_ALGORITHM_RSA_HASH_SHA1 | SC_ALGORITHM_RSA_HASH_SHA256))) { sc_log(ctx, "CKM_RSA_PKCS asked -- use 'AUTHENTICATE' sign operation instead of 'SIGN'"); operation = SC_SEC_OPERATION_AUTHENTICATE; } else if (sign_meth == SC_AC_NEVER) { LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PSO_DST not allowed for this key"); } } if (operation == SC_SEC_OPERATION_SIGN) { prv->op_method = sign_meth; prv->op_ref = sign_ref; } else if (operation == SC_SEC_OPERATION_AUTHENTICATE) { if (auth_meth == SC_AC_NEVER) LOG_TEST_RET(ctx, SC_ERROR_NOT_ALLOWED, "INTERNAL_AUTHENTICATE is not allowed for this key"); prv->op_method = auth_meth; prv->op_ref = auth_ref; } sc_log(ctx, "senv.algorithm 0x%X, senv.algorithm_ref 0x%X", env->algorithm, env->algorithm_ref); sc_log(ctx, "se_num %i, operation 0x%X, algorithm 0x%X, algorithm_ref 0x%X, flags 0x%X; key size %"SC_FORMAT_LEN_SIZE_T"u", se_num, operation, env->algorithm, env->algorithm_ref, env->algorithm_flags, prv->key_size); switch (operation) { case SC_SEC_OPERATION_SIGN: if (!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_PKCS1 specified"); if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) { algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA256); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA256"); cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA2 */ algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA256_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS"); cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA2 */ } else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) { algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA_1); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA1"); cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA1 */ algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA1_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS"); cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1 */ } else { LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA[1,256] specified"); } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_HT); apdu.data = cse_crt_ht; apdu.datalen = sizeof(cse_crt_ht); apdu.lc = sizeof(cse_crt_ht); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "MSE restore error"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_DST); apdu.data = cse_crt_dst; apdu.datalen = sizeof(cse_crt_dst); apdu.lc = sizeof(cse_crt_dst); break; case SC_SEC_OPERATION_AUTHENTICATE: algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports SIGNATURE:RSA_PKCS"); cse_crt_at[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_at[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_AT); apdu.data = cse_crt_at; apdu.datalen = sizeof(cse_crt_at); apdu.lc = sizeof(cse_crt_at); break; case SC_SEC_OPERATION_DECIPHER: rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_DECRYPT, &prv->op_method, &prv->op_ref); LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_PSO_DECRYPT acl"); algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_DECIPHER, CKM_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports DECIPHER:RSA_PKCS"); cse_crt_ct[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_ct[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1 */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_CT); apdu.data = cse_crt_ct; apdu.datalen = sizeof(cse_crt_ct); apdu.lc = sizeof(cse_crt_ct); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "MSE restore error"); prv->security_env = *env; prv->security_env.operation = operation; LOG_FUNC_RETURN(ctx, 0); } static int iasecc_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left) { struct sc_context *ctx = card->ctx; unsigned char buffer[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "CHV PINPAD PIN reference %i", pin_cmd->pin_reference); rv = iasecc_pin_is_verified(card, pin_cmd, tries_left); if (!rv) LOG_FUNC_RETURN(ctx, rv); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } /* When PIN stored length available * P10 verify data contains full template of 'VERIFY PIN' APDU. * Without PIN stored length * pin-pad has to set the Lc and fill PIN data itself. * Not all pin-pads support this case */ pin_cmd->pin1.len = pin_cmd->pin1.stored_length; pin_cmd->pin1.length_offset = 5; memset(buffer, 0xFF, sizeof(buffer)); pin_cmd->pin1.data = buffer; pin_cmd->cmd = SC_PIN_CMD_VERIFY; pin_cmd->flags |= SC_PIN_CMD_USE_PINPAD; /* if (card->reader && card->reader->ops && card->reader->ops->load_message) { rv = card->reader->ops->load_message(card->reader, card->slot, 0, "Here we are!"); sc_log(ctx, "Load message returned %i", rv); } */ rv = iso_ops->pin_cmd(card, pin_cmd, tries_left); sc_log(ctx, "rv %i", rv); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_acl_entry acl = pin_cmd->pin1.acls[IASECC_ACLS_CHV_VERIFY]; struct sc_apdu apdu; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Verify CHV PIN(ref:%i,len:%i,acl:%X:%X)", pin_cmd->pin_reference, pin_cmd->pin1.len, acl.method, acl.key_ref); if (acl.method & IASECC_SCB_METHOD_SM) { rv = iasecc_sm_pin_verify(card, acl.key_ref, pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } if (pin_cmd->pin1.data && !pin_cmd->pin1.len) { sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference); } else if (pin_cmd->pin1.data && pin_cmd->pin1.len) { sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference); apdu.data = pin_cmd->pin1.data; apdu.datalen = pin_cmd->pin1.len; apdu.lc = pin_cmd->pin1.len; } else if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin_cmd->pin1.data && !pin_cmd->pin1.len) { rv = iasecc_chv_verify_pinpad(card, pin_cmd, tries_left); sc_log(ctx, "Result of verifying CHV with PIN pad %i", rv); LOG_FUNC_RETURN(ctx, rv); } else { LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); if (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0) *tries_left = apdu.sw2 & 0x0F; rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_se_at_to_chv_reference(struct sc_card *card, unsigned reference, unsigned *chv_reference) { struct sc_context *ctx = card->ctx; struct iasecc_se_info se; struct sc_crt crt; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "SE reference %i", reference); if (reference > IASECC_SE_REF_MAX) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); memset(&se, 0, sizeof(se)); se.reference = reference; rv = iasecc_se_get_info(card, &se); LOG_TEST_RET(ctx, rv, "SDO get data error"); memset(&crt, 0, sizeof(crt)); crt.tag = IASECC_CRT_TAG_AT; crt.usage = IASECC_UQB_AT_USER_PASSWORD; rv = iasecc_se_get_crt(card, &se, &crt); LOG_TEST_RET(ctx, rv, "no authentication template for USER PASSWORD"); if (chv_reference) *chv_reference = crt.refs[0]; sc_file_free(se.df); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY]; int rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; LOG_FUNC_CALLED(ctx); if (pin_cmd_data->pin_type != SC_AC_CHV) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification"); sc_log(ctx, "Verify ACL(method:%X;ref:%X)", acl.method, acl.key_ref); if (acl.method != IASECC_SCB_ALWAYS) LOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED); pin_cmd = *pin_cmd_data; pin_cmd.pin1.data = (unsigned char *)""; pin_cmd.pin1.len = 0; rv = iasecc_chv_verify(card, &pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_verify(struct sc_card *card, unsigned type, unsigned reference, const unsigned char *data, size_t data_len, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned chv_ref = reference; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Verify PIN(type:%X,ref:%i,data(len:%"SC_FORMAT_LEN_SIZE_T"u,%p)", type, reference, data_len, data); if (type == SC_AC_AUT) { rv = iasecc_sm_external_authentication(card, reference, tries_left); LOG_FUNC_RETURN(ctx, rv); } else if (type == SC_AC_SCB) { if (reference & IASECC_SCB_METHOD_USER_AUTH) { type = SC_AC_SEN; reference = reference & IASECC_SCB_METHOD_MASK_REF; } else { sc_log(ctx, "Do not try to verify non CHV PINs"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } } if (type == SC_AC_SEN) { rv = iasecc_se_at_to_chv_reference(card, reference, &chv_ref); LOG_TEST_RET(ctx, rv, "SE AT to CHV reference error"); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = chv_ref; pin_cmd.cmd = SC_PIN_CMD_VERIFY; rv = iasecc_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); pin_cmd.pin1.data = data; pin_cmd.pin1.len = data_len; rv = iasecc_pin_is_verified(card, &pin_cmd, tries_left); if (data && !data_len) LOG_FUNC_RETURN(ctx, rv); if (!rv) { if (iasecc_chv_cache_is_verified(card, &pin_cmd)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); } else if (rv != SC_ERROR_PIN_CODE_INCORRECT && rv != SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) { LOG_FUNC_RETURN(ctx, rv); } iasecc_chv_cache_clean(card, &pin_cmd); rv = iasecc_chv_verify(card, &pin_cmd, tries_left); LOG_TEST_RET(ctx, rv, "PIN CHV verification error"); rv = iasecc_chv_cache_verified(card, &pin_cmd); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_chv_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned char pin1_data[0x100], pin2_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "CHV PINPAD PIN reference %i", reference); memset(pin1_data, 0xFF, sizeof(pin1_data)); memset(pin2_data, 0xFF, sizeof(pin2_data)); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = reference; pin_cmd.cmd = SC_PIN_CMD_CHANGE; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD; rv = iasecc_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); /* Some pin-pads do not support mode with Lc=0. * Give them a chance to work with some cards. */ if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length)) pin_cmd.pin1.len = pin_cmd.pin1.stored_length; else pin_cmd.pin1.len = 0; pin_cmd.pin1.length_offset = 5; pin_cmd.pin1.data = pin1_data; memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1)); pin_cmd.pin2.data = pin2_data; sc_log(ctx, "PIN1 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length, pin_cmd.pin1.stored_length); sc_log(ctx, "PIN2 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length, pin_cmd.pin2.stored_length); rv = iso_ops->pin_cmd(card, &pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } #if 0 static int iasecc_chv_set_pinpad(struct sc_card *card, unsigned char reference) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned char pin_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Set CHV PINPAD PIN reference %i", reference); memset(pin_data, 0xFF, sizeof(pin_data)); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = reference; pin_cmd.cmd = SC_PIN_CMD_UNBLOCK; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD; rv = iasecc_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length)) pin_cmd.pin1.len = pin_cmd.pin1.stored_length; else pin_cmd.pin1.len = 0; pin_cmd.pin1.length_offset = 5; pin_cmd.pin1.data = pin_data; memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1)); memset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1)); pin_cmd.flags |= SC_PIN_CMD_IMPLICIT_CHANGE; sc_log(ctx, "PIN1(max:%i,min:%i)", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length); sc_log(ctx, "PIN2(max:%i,min:%i)", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length); rv = iso_ops->pin_cmd(card, &pin_cmd, NULL); LOG_FUNC_RETURN(ctx, rv); } #endif static int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data) { struct sc_context *ctx = card->ctx; struct sc_file *save_current_df = NULL, *save_current_ef = NULL; struct iasecc_sdo sdo; struct sc_path path; unsigned ii; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_pin_get_policy(card:%p)", card); if (data->pin_type != SC_AC_CHV) { sc_log(ctx, "To unblock PIN it's CHV reference should be presented"); LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } if (card->cache.valid && card->cache.current_df) { sc_file_dup(&save_current_df, card->cache.current_df); if (save_current_df == NULL) { rv = SC_ERROR_OUT_OF_MEMORY; sc_log(ctx, "Cannot duplicate current DF file"); goto err; } } if (card->cache.valid && card->cache.current_ef) { sc_file_dup(&save_current_ef, card->cache.current_ef); if (save_current_ef == NULL) { rv = SC_ERROR_OUT_OF_MEMORY; sc_log(ctx, "Cannot duplicate current EF file"); goto err; } } if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) { sc_format_path("3F00", &path); path.type = SC_PATH_TYPE_FILE_ID; rv = iasecc_select_file(card, &path, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "Unable to select MF"); } memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_CHV; sdo.sdo_ref = data->pin_reference & ~IASECC_OBJECT_REF_LOCAL; sc_log(ctx, "iasecc_pin_get_policy() reference %i", sdo.sdo_ref); rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_GOTO_ERR(ctx, rv, "Cannot get SDO PIN data"); if (sdo.docp.acls_contact.size == 0) { rv = SC_ERROR_INVALID_DATA; sc_log(ctx, "Extremely strange ... there is no ACLs"); goto err; } sc_log(ctx, "iasecc_pin_get_policy() sdo.docp.size.size %"SC_FORMAT_LEN_SIZE_T"u", sdo.docp.size.size); for (ii=0; ii<sizeof(sdo.docp.scbs); ii++) { struct iasecc_se_info se; unsigned char scb = sdo.docp.scbs[ii]; struct sc_acl_entry *acl = &data->pin1.acls[ii]; int crt_num = 0; memset(&se, 0, sizeof(se)); memset(&acl->crts, 0, sizeof(acl->crts)); sc_log(ctx, "iasecc_pin_get_policy() set info acls: SCB 0x%X", scb); /* acl->raw_value = scb; */ acl->method = scb & IASECC_SCB_METHOD_MASK; acl->key_ref = scb & IASECC_SCB_METHOD_MASK_REF; if (scb==0 || scb==0xFF) continue; if (se.reference != (int)acl->key_ref) { memset(&se, 0, sizeof(se)); se.reference = acl->key_ref; rv = iasecc_se_get_info(card, &se); LOG_TEST_GOTO_ERR(ctx, rv, "SDO get data error"); } if (scb & IASECC_SCB_METHOD_USER_AUTH) { rv = iasecc_se_get_crt_by_usage(card, &se, IASECC_CRT_TAG_AT, IASECC_UQB_AT_USER_PASSWORD, &acl->crts[crt_num]); LOG_TEST_GOTO_ERR(ctx, rv, "no authentication template for 'USER PASSWORD'"); sc_log(ctx, "iasecc_pin_get_policy() scb:0x%X; sdo_ref:[%i,%i,...]", scb, acl->crts[crt_num].refs[0], acl->crts[crt_num].refs[1]); crt_num++; } if (scb & (IASECC_SCB_METHOD_SM | IASECC_SCB_METHOD_EXT_AUTH)) { sc_log(ctx, "'SM' and 'EXTERNAL AUTHENTICATION' protection methods are not supported: SCB:0x%X", scb); /* Set to 'NEVER' if all conditions are needed or * there is no user authentication method allowed */ if (!crt_num || (scb & IASECC_SCB_METHOD_NEED_ALL)) acl->method = SC_AC_NEVER; continue; } sc_file_free(se.df); } if (sdo.data.chv.size_max.value) data->pin1.max_length = *sdo.data.chv.size_max.value; if (sdo.data.chv.size_min.value) data->pin1.min_length = *sdo.data.chv.size_min.value; if (sdo.docp.tries_maximum.value) data->pin1.max_tries = *sdo.docp.tries_maximum.value; if (sdo.docp.tries_remaining.value) data->pin1.tries_left = *sdo.docp.tries_remaining.value; if (sdo.docp.size.value) { for (ii=0; ii<sdo.docp.size.size; ii++) data->pin1.stored_length = ((data->pin1.stored_length) << 8) + *(sdo.docp.size.value + ii); } data->pin1.encoding = SC_PIN_ENCODING_ASCII; data->pin1.offset = 5; data->pin1.logged_in = SC_PIN_STATE_UNKNOWN; sc_log(ctx, "PIN policy: size max/min %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u, tries max/left %i/%i", data->pin1.max_length, data->pin1.min_length, data->pin1.max_tries, data->pin1.tries_left); iasecc_sdo_free_fields(card, &sdo); if (save_current_df) { sc_log(ctx, "iasecc_pin_get_policy() restore current DF"); rv = iasecc_select_file(card, &save_current_df->path, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved DF"); } if (save_current_ef) { sc_log(ctx, "iasecc_pin_get_policy() restore current EF"); rv = iasecc_select_file(card, &save_current_ef->path, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved EF"); } err: sc_file_free(save_current_df); sc_file_free(save_current_ef); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct iasecc_sdo_update update; struct iasecc_sdo sdo; unsigned scb; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Change keyset(ref:%i,lengths:%i)", data->pin_reference, data->pin2.len); if (!data->pin2.data || data->pin2.len < 32) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Needs at least 32 bytes for a new keyset value"); memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_KEYSET; sdo.sdo_ref = data->pin_reference; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "Cannot get keyset data"); if (sdo.docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs"); scb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA]; iasecc_sdo_free_fields(card, &sdo); sc_log(ctx, "SCB:0x%X", scb); if (!(scb & IASECC_SCB_METHOD_SM)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Other then protected by SM, the keyset change is not supported"); memset(&update, 0, sizeof(update)); update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA; update.sdo_class = sdo.sdo_class; update.sdo_ref = sdo.sdo_ref; update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG; update.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC; /* FIXME is it safe to modify the const value here? */ update.fields[0].value = (unsigned char *) data->pin2.data; update.fields[0].size = 16; update.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG; update.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC; /* FIXME is it safe to modify the const value here? */ update.fields[1].value = (unsigned char *) data->pin2.data + 16; update.fields[1].size = 16; rv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned reference = data->pin_reference; unsigned char pin_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Change PIN(ref:%i,type:0x%X,lengths:%i/%i)", reference, data->pin_type, data->pin1.len, data->pin2.len); if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD)) { if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) { rv = iasecc_chv_change_pinpad(card, reference, tries_left); sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv); LOG_FUNC_RETURN(ctx, rv); } } if (!data->pin1.data && data->pin1.len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN1 arguments"); if (!data->pin2.data && data->pin2.len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN2 arguments"); rv = iasecc_pin_verify(card, data->pin_type, reference, data->pin1.data, data->pin1.len, tries_left); sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) pin_verify returned %i", rv); LOG_TEST_RET(ctx, rv, "PIN verification error"); if ((unsigned)(data->pin1.len + data->pin2.len) > sizeof(pin_data)) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small for the 'Change PIN' data"); if (data->pin1.data) memcpy(pin_data, data->pin1.data, data->pin1.len); if (data->pin2.data) memcpy(pin_data + data->pin1.len, data->pin2.data, data->pin2.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0, reference); apdu.data = pin_data; apdu.datalen = data->pin1.len + data->pin2.len; apdu.lc = apdu.datalen; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_file *save_current = NULL; struct iasecc_sdo sdo; struct sc_apdu apdu; unsigned reference, scb; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Reset PIN(ref:%i,lengths:%i/%i)", data->pin_reference, data->pin1.len, data->pin2.len); if (data->pin_type != SC_AC_CHV) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Unblock procedure can be used only with the PINs of type CHV"); reference = data->pin_reference; if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) { struct sc_path path; sc_file_dup(&save_current, card->cache.current_df); if (save_current == NULL) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file"); sc_format_path("3F00", &path); path.type = SC_PATH_TYPE_FILE_ID; rv = iasecc_select_file(card, &path, NULL); LOG_TEST_RET(ctx, rv, "Unable to select MF"); } memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_CHV; sdo.sdo_ref = reference & ~IASECC_OBJECT_REF_LOCAL; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "Cannot get PIN data"); if (sdo.docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Extremely strange ... there are no ACLs"); scb = sdo.docp.scbs[IASECC_ACLS_CHV_RESET]; do { unsigned need_all = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; unsigned char se_num = scb & IASECC_SCB_METHOD_MASK_REF; if (scb & IASECC_SCB_METHOD_USER_AUTH) { sc_log(ctx, "Verify PIN in SE %X", se_num); rv = iasecc_pin_verify(card, SC_AC_SEN, se_num, data->pin1.data, data->pin1.len, tries_left); LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() verify PUK error"); if (!need_all) break; } if (scb & IASECC_SCB_METHOD_SM) { rv = iasecc_sm_pin_reset(card, se_num, data); LOG_FUNC_RETURN(ctx, rv); } if (scb & IASECC_SCB_METHOD_EXT_AUTH) { rv = iasecc_sm_external_authentication(card, reference, tries_left); LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() external authentication error"); } } while(0); iasecc_sdo_free_fields(card, &sdo); if (data->pin2.len) { sc_log(ctx, "Reset PIN %X and set new value", reference); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference); apdu.data = data->pin2.data; apdu.datalen = data->pin2.len; apdu.lc = apdu.datalen; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); } else if (data->pin2.data) { sc_log(ctx, "Reset PIN %X and set new value", reference); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); } else { sc_log(ctx, "Reset PIN %X and set new value with PIN-PAD", reference); #if 0 rv = iasecc_chv_set_pinpad(card, reference); LOG_TEST_RET(ctx, rv, "Reset PIN failed"); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Reset retry counter with PIN PAD not supported "); #endif } if (save_current) { rv = iasecc_select_file(card, &save_current->path, NULL); LOG_TEST_RET(ctx, rv, "Cannot return to saved PATH"); } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_pin_cmd() cmd 0x%X, PIN type 0x%X, PIN reference %i, PIN-1 %p:%i, PIN-2 %p:%i", data->cmd, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, data->pin2.data, data->pin2.len); switch (data->cmd) { case SC_PIN_CMD_VERIFY: rv = iasecc_pin_verify(card, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, tries_left); break; case SC_PIN_CMD_CHANGE: if (data->pin_type == SC_AC_AUT) rv = iasecc_keyset_change(card, data, tries_left); else rv = iasecc_pin_change(card, data, tries_left); break; case SC_PIN_CMD_UNBLOCK: rv = iasecc_pin_reset(card, data, tries_left); break; case SC_PIN_CMD_GET_INFO: rv = iasecc_pin_get_policy(card, data); break; default: sc_log(ctx, "Other pin commands not supported yet: 0x%X", data->cmd); rv = SC_ERROR_NOT_SUPPORTED; } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial) { struct sc_context *ctx = card->ctx; struct sc_iin *iin = &card->serialnr.iin; struct sc_apdu apdu; unsigned char rbuf[0xC0]; size_t ii, offs; int rv; LOG_FUNC_CALLED(ctx); if (card->serialnr.len) goto end; memset(&card->serialnr, 0, sizeof(card->serialnr)); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0); apdu.le = sizeof(rbuf); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed"); if (rbuf[0] != ISO7812_PAN_SN_TAG) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error"); iin->mii = (rbuf[2] >> 4) & 0x0F; iin->country = 0; for (ii=5; ii<8; ii++) { iin->country *= 10; iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F; } iin->issuer_id = 0; for (ii=8; ii<10; ii++) { iin->issuer_id *= 10; iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F; } offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0; if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { /* 5A 0A 92 50 00 20 10 10 25 00 01 3F */ /* 00 02 01 01 02 50 00 13 */ for (ii=0; (ii < rbuf[1] - offs) && (ii + offs + 2 < sizeof(rbuf)); ii++) *(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4) + ((rbuf[ii + offs + 2] & 0xF0) >> 4) ; card->serialnr.len = ii; } else { for (ii=0; ii < rbuf[1] - offs; ii++) *(card->serialnr.value + ii) = rbuf[ii + offs + 2]; card->serialnr.len = ii; } do { char txt[0x200]; for (ii=0;ii<card->serialnr.len;ii++) sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii)); sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id); } while(0); end: if (serial) memcpy(serial, &card->serialnr, sizeof(*serial)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_sdo_create(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char *data = NULL, sdo_class = sdo->sdo_class; struct iasecc_sdo_update update; struct iasecc_extended_tlv *field = NULL; int rv = SC_ERROR_NOT_SUPPORTED, data_len; LOG_FUNC_CALLED(ctx); if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data"); sc_log(ctx, "iasecc_sdo_create(card:%p) %02X%02X%02X", card, IASECC_SDO_TAG_HEADER, sdo->sdo_class | 0x80, sdo->sdo_ref); data_len = iasecc_sdo_encode_create(ctx, sdo, &data); LOG_TEST_RET(ctx, data_len, "iasecc_sdo_create() cannot encode SDO create data"); sc_log(ctx, "iasecc_sdo_create() create data(%i):%s", data_len, sc_dump_hex(data, data_len)); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = data; apdu.datalen = data_len; apdu.lc = data_len; apdu.flags |= SC_APDU_FLAGS_CHAINING; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "iasecc_sdo_create() SDO put data error"); memset(&update, 0, sizeof(update)); update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA; update.sdo_class = sdo->sdo_class; update.sdo_ref = sdo->sdo_ref; if (sdo_class == IASECC_SDO_CLASS_RSA_PRIVATE) { update.fields[0] = sdo->data.prv_key.compulsory; update.fields[0].parent_tag = IASECC_SDO_PRVKEY_TAG; field = &sdo->data.prv_key.compulsory; } else if (sdo_class == IASECC_SDO_CLASS_RSA_PUBLIC) { update.fields[0] = sdo->data.pub_key.compulsory; update.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG; field = &sdo->data.pub_key.compulsory; } else if (sdo_class == IASECC_SDO_CLASS_KEYSET) { update.fields[0] = sdo->data.keyset.compulsory; update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG; field = &sdo->data.keyset.compulsory; } if (update.fields[0].value && !update.fields[0].on_card) { rv = iasecc_sdo_put_data(card, &update); LOG_TEST_RET(ctx, rv, "failed to update 'Compulsory usage' data"); if (field) field->on_card = 1; } free(data); LOG_FUNC_RETURN(ctx, rv); } /* Oberthur's specific */ static int iasecc_sdo_delete(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char data[6] = { 0x70, 0x04, 0xBF, 0xFF, 0xFF, 0x00 }; int rv; LOG_FUNC_CALLED(ctx); if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data"); data[2] = IASECC_SDO_TAG_HEADER; data[3] = sdo->sdo_class | 0x80; data[4] = sdo->sdo_ref; sc_log(ctx, "delete SDO %02X%02X%02X", data[2], data[3], data[4]); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = data; apdu.datalen = sizeof(data); apdu.lc = sizeof(data); apdu.flags |= SC_APDU_FLAGS_CHAINING; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "delete SDO error"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; int ii, rv; LOG_FUNC_CALLED(ctx); if (update->magic != SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO update data"); for(ii=0; update->fields[ii].tag && ii < IASECC_SDO_TAGS_UPDATE_MAX; ii++) { unsigned char *encoded = NULL; int encoded_len; encoded_len = iasecc_sdo_encode_update_field(ctx, update->sdo_class, update->sdo_ref, &update->fields[ii], &encoded); sc_log(ctx, "iasecc_sdo_put_data() encode[%i]; tag %X; encoded_len %i", ii, update->fields[ii].tag, encoded_len); LOG_TEST_RET(ctx, encoded_len, "Cannot encode update data"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = encoded; apdu.datalen = encoded_len; apdu.lc = encoded_len; apdu.flags |= SC_APDU_FLAGS_CHAINING; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO put data error"); free(encoded); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update) { struct sc_context *ctx = card->ctx; unsigned char scb; int rv; LOG_FUNC_CALLED(ctx); if (update->sdo_prv_key) { sc_log(ctx, "encode private rsa in %p", &update->update_prv); rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv); LOG_TEST_RET(ctx, rv, "failed to encode update of RSA private key"); } if (update->sdo_pub_key) { sc_log(ctx, "encode public rsa in %p", &update->update_pub); if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { if (update->sdo_pub_key->data.pub_key.cha.value) { free(update->sdo_pub_key->data.pub_key.cha.value); memset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha)); } } rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub); LOG_TEST_RET(ctx, rv, "failed to encode update of RSA public key"); } if (update->sdo_prv_key) { sc_log(ctx, "reference of the private key to store: %X", update->sdo_prv_key->sdo_ref); if (update->sdo_prv_key->docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "extremely strange ... there are no ACLs"); scb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA]; sc_log(ctx, "'UPDATE PRIVATE RSA' scb 0x%X", scb); do { unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; if ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions) break; if (scb & IASECC_SCB_METHOD_EXT_AUTH) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); if (scb & IASECC_SCB_METHOD_SM) { #ifdef ENABLE_SM rv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update); LOG_FUNC_RETURN(ctx, rv); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "built without support of Secure-Messaging"); #endif } } while(0); rv = iasecc_sdo_put_data(card, &update->update_prv); LOG_TEST_RET(ctx, rv, "failed to update of RSA private key"); } if (update->sdo_pub_key) { sc_log(ctx, "reference of the public key to store: %X", update->sdo_pub_key->sdo_ref); rv = iasecc_sdo_put_data(card, &update->update_pub); LOG_TEST_RET(ctx, rv, "failed to update of RSA public key"); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_sdo_tag_from_class(unsigned sdo_class) { switch (sdo_class & ~IASECC_OBJECT_REF_LOCAL) { case IASECC_SDO_CLASS_CHV: return IASECC_SDO_CHV_TAG; case IASECC_SDO_CLASS_RSA_PRIVATE: return IASECC_SDO_PRVKEY_TAG; case IASECC_SDO_CLASS_RSA_PUBLIC: return IASECC_SDO_PUBKEY_TAG; case IASECC_SDO_CLASS_SE: return IASECC_SDO_CLASS_SE; case IASECC_SDO_CLASS_KEYSET: return IASECC_SDO_KEYSET_TAG; } return -1; } static int iasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char sbuf[0x100]; size_t offs = sizeof(sbuf) - 1; unsigned char rbuf[0x400]; int rv; LOG_FUNC_CALLED(ctx); sbuf[offs--] = 0x80; sbuf[offs--] = sdo_tag & 0xFF; if ((sdo_tag >> 8) & 0xFF) sbuf[offs--] = (sdo_tag >> 8) & 0xFF; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs--] = sdo->sdo_ref & 0x9F; sbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL; sbuf[offs--] = IASECC_SDO_TAG_HEADER; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs--] = IASECC_SDO_TEMPLATE_TAG; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs] = 0x4D; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF); apdu.data = sbuf + offs; apdu.datalen = sizeof(sbuf) - offs; apdu.lc = sizeof(sbuf) - offs; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO get data error"); rv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo); LOG_TEST_RET(ctx, rv, "cannot parse SDO data"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; int rv, sdo_tag; LOG_FUNC_CALLED(ctx); sdo_tag = iasecc_sdo_tag_from_class(sdo->sdo_class); rv = iasecc_sdo_get_tagged_data(card, sdo_tag, sdo); /* When there is no public data 'GET DATA' returns error */ if (rv != SC_ERROR_INCORRECT_PARAMETERS) LOG_TEST_RET(ctx, rv, "cannot parse ECC SDO data"); rv = iasecc_sdo_get_tagged_data(card, IASECC_DOCP_TAG, sdo); LOG_TEST_RET(ctx, rv, "cannot parse ECC DOCP data"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_sdo_generate(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct iasecc_sdo_update update_pubkey; struct sc_apdu apdu; unsigned char scb, sbuf[5], rbuf[0x400], exponent[3] = {0x01, 0x00, 0x01}; int offs = 0, rv = SC_ERROR_NOT_SUPPORTED; LOG_FUNC_CALLED(ctx); if (sdo->sdo_class != IASECC_SDO_CLASS_RSA_PRIVATE) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "For a moment, only RSA_PRIVATE class can be accepted for the SDO generation"); if (sdo->docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs"); scb = sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE]; sc_log(ctx, "'generate RSA key' SCB 0x%X", scb); do { unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; if (scb & IASECC_SCB_METHOD_USER_AUTH) if (!all_conditions) break; if (scb & IASECC_SCB_METHOD_EXT_AUTH) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); if (scb & IASECC_SCB_METHOD_SM) { rv = iasecc_sm_rsa_generate(card, scb & IASECC_SCB_METHOD_MASK_REF, sdo); LOG_FUNC_RETURN(ctx, rv); } } while(0); memset(&update_pubkey, 0, sizeof(update_pubkey)); update_pubkey.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA; update_pubkey.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC; update_pubkey.sdo_ref = sdo->sdo_ref; update_pubkey.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG; update_pubkey.fields[0].tag = IASECC_SDO_PUBKEY_TAG_E; update_pubkey.fields[0].value = exponent; update_pubkey.fields[0].size = sizeof(exponent); rv = iasecc_sdo_put_data(card, &update_pubkey); LOG_TEST_RET(ctx, rv, "iasecc_sdo_generate() update SDO public key failed"); offs = 0; sbuf[offs++] = IASECC_SDO_TEMPLATE_TAG; sbuf[offs++] = 0x03; sbuf[offs++] = IASECC_SDO_TAG_HEADER; sbuf[offs++] = IASECC_SDO_CLASS_RSA_PRIVATE | IASECC_OBJECT_REF_LOCAL; sbuf[offs++] = sdo->sdo_ref & ~IASECC_OBJECT_REF_LOCAL; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00); apdu.data = sbuf; apdu.datalen = offs; apdu.lc = offs; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO get data error"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_get_chv_reference_from_se(struct sc_card *card, int *se_reference) { struct sc_context *ctx = card->ctx; struct iasecc_se_info se; struct sc_crt crt; int rv; LOG_FUNC_CALLED(ctx); if (!se_reference) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments"); memset(&se, 0, sizeof(se)); se.reference = *se_reference; rv = iasecc_se_get_info(card, &se); LOG_TEST_RET(ctx, rv, "get SE info error"); memset(&crt, 0, sizeof(crt)); crt.tag = IASECC_CRT_TAG_AT; crt.usage = IASECC_UQB_AT_USER_PASSWORD; rv = iasecc_se_get_crt(card, &se, &crt); LOG_TEST_RET(ctx, rv, "Cannot get 'USER PASSWORD' authentication template"); sc_file_free(se.df); LOG_FUNC_RETURN(ctx, crt.refs[0]); } static int iasecc_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { struct sc_context *ctx = card->ctx; struct iasecc_sdo *sdo = (struct iasecc_sdo *) ptr; switch (cmd) { case SC_CARDCTL_GET_SERIALNR: return iasecc_get_serialnr(card, (struct sc_serial_number *)ptr); case SC_CARDCTL_IASECC_SDO_CREATE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_CREATE: sdo_class %X", sdo->sdo_class); return iasecc_sdo_create(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_IASECC_SDO_DELETE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_DELETE: sdo_class %X", sdo->sdo_class); return iasecc_sdo_delete(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_IASECC_SDO_PUT_DATA: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_PUT_DATA: sdo_class %X", sdo->sdo_class); return iasecc_sdo_put_data(card, (struct iasecc_sdo_update *) ptr); case SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA"); return iasecc_sdo_key_rsa_put_data(card, (struct iasecc_sdo_rsa_update *) ptr); case SC_CARDCTL_IASECC_SDO_GET_DATA: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class); return iasecc_sdo_get_data(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_IASECC_SDO_GENERATE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class); return iasecc_sdo_generate(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_GET_SE_INFO: sc_log(ctx, "CMD SC_CARDCTL_GET_SE_INFO: sdo_class %X", sdo->sdo_class); return iasecc_se_get_info(card, (struct iasecc_se_info *) ptr); case SC_CARDCTL_GET_CHV_REFERENCE_IN_SE: sc_log(ctx, "CMD SC_CARDCTL_GET_CHV_REFERENCE_IN_SE"); return iasecc_get_chv_reference_from_se(card, (int *)ptr); case SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE"); return iasecc_get_free_reference(card, (struct iasecc_ctl_get_free_reference *)ptr); } return SC_ERROR_NOT_SUPPORTED; } static int iasecc_decipher(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char sbuf[0x200]; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE]; size_t offs; int rv; LOG_FUNC_CALLED(ctx); sc_log(card->ctx, "crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u", in_len, out_len); if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); offs = 0; sbuf[offs++] = 0x81; memcpy(sbuf + offs, in, in_len); offs += in_len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.flags |= SC_APDU_FLAGS_CHAINING; apdu.data = sbuf; apdu.datalen = offs; apdu.lc = offs; apdu.resp = resp; apdu.resplen = sizeof(resp); apdu.le = 256; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Card returned error"); if (out_len > apdu.resplen) out_len = apdu.resplen; memcpy(out, apdu.resp, out_len); rv = out_len; LOG_FUNC_RETURN(ctx, rv); } static int iasecc_qsign_data_sha1(struct sc_context *ctx, const unsigned char *in, size_t in_len, struct iasecc_qsign_data *out) { SHA_CTX sha; SHA_LONG pre_hash_Nl, *hh[5] = { &sha.h0, &sha.h1, &sha.h2, &sha.h3, &sha.h4 }; int jj, ii; int hh_size = sizeof(SHA_LONG), hh_num = SHA_DIGEST_LENGTH / sizeof(SHA_LONG); LOG_FUNC_CALLED(ctx); if (!in || !in_len || !out) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u", in_len); memset(out, 0, sizeof(struct iasecc_qsign_data)); SHA1_Init(&sha); SHA1_Update(&sha, in, in_len); for (jj=0; jj<hh_num; jj++) for(ii=0; ii<hh_size; ii++) out->pre_hash[jj*hh_size + ii] = ((*hh[jj] >> 8*(hh_size-1-ii)) & 0xFF); out->pre_hash_size = SHA_DIGEST_LENGTH; sc_log(ctx, "Pre SHA1:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size)); pre_hash_Nl = sha.Nl - (sha.Nl % (sizeof(sha.data) * 8)); for (ii=0; ii<hh_size; ii++) { out->counter[ii] = (sha.Nh >> 8*(hh_size-1-ii)) &0xFF; out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF; } for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++) out->counter_long = out->counter_long*0x100 + out->counter[ii]; sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter))); if (sha.num) { memcpy(out->last_block, in + in_len - sha.num, sha.num); out->last_block_size = sha.num; sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s", out->last_block_size, sc_dump_hex(out->last_block, out->last_block_size)); } SHA1_Final(out->hash, &sha); out->hash_size = SHA_DIGEST_LENGTH; sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } #if OPENSSL_VERSION_NUMBER >= 0x00908000L static int iasecc_qsign_data_sha256(struct sc_context *ctx, const unsigned char *in, size_t in_len, struct iasecc_qsign_data *out) { SHA256_CTX sha256; SHA_LONG pre_hash_Nl; int jj, ii; int hh_size = sizeof(SHA_LONG), hh_num = SHA256_DIGEST_LENGTH / sizeof(SHA_LONG); LOG_FUNC_CALLED(ctx); if (!in || !in_len || !out) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u", in_len); memset(out, 0, sizeof(struct iasecc_qsign_data)); SHA256_Init(&sha256); SHA256_Update(&sha256, in, in_len); for (jj=0; jj<hh_num; jj++) for(ii=0; ii<hh_size; ii++) out->pre_hash[jj*hh_size + ii] = ((sha256.h[jj] >> 8*(hh_size-1-ii)) & 0xFF); out->pre_hash_size = SHA256_DIGEST_LENGTH; sc_log(ctx, "Pre hash:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size)); pre_hash_Nl = sha256.Nl - (sha256.Nl % (sizeof(sha256.data) * 8)); for (ii=0; ii<hh_size; ii++) { out->counter[ii] = (sha256.Nh >> 8*(hh_size-1-ii)) &0xFF; out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF; } for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++) out->counter_long = out->counter_long*0x100 + out->counter[ii]; sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter))); if (sha256.num) { memcpy(out->last_block, in + in_len - sha256.num, sha256.num); out->last_block_size = sha256.num; sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s", out->last_block_size, sc_dump_hex(out->last_block, out->last_block_size)); } SHA256_Final(out->hash, &sha256); out->hash_size = SHA256_DIGEST_LENGTH; sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } #endif static int iasecc_compute_signature_dst(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_security_env *env = &prv->security_env; struct iasecc_qsign_data qsign_data; struct sc_apdu apdu; size_t offs = 0, hash_len = 0; unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_compute_signature_dst() input length %"SC_FORMAT_LEN_SIZE_T"u", in_len); if (env->operation != SC_SEC_OPERATION_SIGN) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_SIGN"); else if (!(prv->key_size & 0x1E0) || (prv->key_size & ~0x1E0)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid key size for SC_SEC_OPERATION_SIGN"); memset(&qsign_data, 0, sizeof(qsign_data)); if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) { rv = iasecc_qsign_data_sha1(card->ctx, in, in_len, &qsign_data); } else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) { #if OPENSSL_VERSION_NUMBER >= 0x00908000L rv = iasecc_qsign_data_sha256(card->ctx, in, in_len, &qsign_data); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "SHA256 is not supported by OpenSSL previous to v0.9.8"); #endif } else LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA1 or RSA_HASH_SHA256 algorithm"); LOG_TEST_RET(ctx, rv, "Cannot get QSign data"); sc_log(ctx, "iasecc_compute_signature_dst() hash_len %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u", hash_len, prv->key_size); memset(sbuf, 0, sizeof(sbuf)); sbuf[offs++] = 0x90; if (qsign_data.counter_long) { sbuf[offs++] = qsign_data.hash_size + 8; memcpy(sbuf + offs, qsign_data.pre_hash, qsign_data.pre_hash_size); offs += qsign_data.pre_hash_size; memcpy(sbuf + offs, qsign_data.counter, sizeof(qsign_data.counter)); offs += sizeof(qsign_data.counter); } else { sbuf[offs++] = 0; } sbuf[offs++] = 0x80; sbuf[offs++] = qsign_data.last_block_size; memcpy(sbuf + offs, qsign_data.last_block, qsign_data.last_block_size); offs += qsign_data.last_block_size; sc_log(ctx, "iasecc_compute_signature_dst() offs %"SC_FORMAT_LEN_SIZE_T"u; OP(meth:%X,ref:%X)", offs, prv->op_method, prv->op_ref); if (prv->op_method == SC_AC_SCB && (prv->op_ref & IASECC_SCB_METHOD_SM)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x90, 0xA0); apdu.data = sbuf; apdu.datalen = offs; apdu.lc = offs; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Compute signature failed"); sc_log(ctx, "iasecc_compute_signature_dst() partial hash OK"); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x2A, 0x9E, 0x9A); apdu.resp = rbuf; apdu.resplen = prv->key_size; apdu.le = prv->key_size; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Compute signature failed"); sc_log(ctx, "iasecc_compute_signature_dst() DST resplen %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen > out_len) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Result buffer too small for the DST signature"); memcpy(out, apdu.resp, apdu.resplen); LOG_FUNC_RETURN(ctx, apdu.resplen); } static int iasecc_compute_signature_at(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_security_env *env = &prv->security_env; struct sc_apdu apdu; size_t offs = 0, sz = 0; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int rv; LOG_FUNC_CALLED(ctx); if (env->operation != SC_SEC_OPERATION_AUTHENTICATE) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_AUTHENTICATE"); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00); apdu.datalen = in_len; apdu.data = in; apdu.lc = in_len; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Compute signature failed"); do { if (offs + apdu.resplen > out_len) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to return signature"); memcpy(out + offs, rbuf, apdu.resplen); offs += apdu.resplen; if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) break; if (apdu.sw1 == 0x61) { sz = apdu.sw2 == 0x00 ? 0x100 : apdu.sw2; rv = iso_ops->get_response(card, &sz, rbuf); LOG_TEST_RET(ctx, rv, "Get response error"); apdu.resplen = rv; } else { LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Impossible error: SW1 is not 0x90 neither 0x61"); } } while(rv > 0); LOG_FUNC_RETURN(ctx, offs); } static int iasecc_compute_signature(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx; struct iasecc_private_data *prv; struct sc_security_env *env; if (!card || !in || !out) return SC_ERROR_INVALID_ARGUMENTS; ctx = card->ctx; prv = (struct iasecc_private_data *) card->drv_data; env = &prv->security_env; LOG_FUNC_CALLED(ctx); sc_log(ctx, "inlen %"SC_FORMAT_LEN_SIZE_T"u, outlen %"SC_FORMAT_LEN_SIZE_T"u", in_len, out_len); if (env->operation == SC_SEC_OPERATION_SIGN) return iasecc_compute_signature_dst(card, in, in_len, out, out_len); else if (env->operation == SC_SEC_OPERATION_AUTHENTICATE) return iasecc_compute_signature_at(card, in, in_len, out, out_len); LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } static int iasecc_read_public_key(struct sc_card *card, unsigned type, struct sc_path *key_path, unsigned ref, unsigned size, unsigned char **out, size_t *out_len) { struct sc_context *ctx = card->ctx; struct iasecc_sdo sdo; struct sc_pkcs15_bignum bn[2]; struct sc_pkcs15_pubkey_rsa rsa_key; int rv; LOG_FUNC_CALLED(ctx); if (type != SC_ALGORITHM_RSA) LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); sc_log(ctx, "read public kay(ref:%i;size:%i)", ref, size); memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC; sdo.sdo_ref = ref & ~IASECC_OBJECT_REF_LOCAL; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "failed to read public key: cannot get RSA SDO data"); if (out) *out = NULL; if (out_len) *out_len = 0; bn[0].data = (unsigned char *) malloc(sdo.data.pub_key.n.size); if (!bn[0].data) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate modulus"); bn[0].len = sdo.data.pub_key.n.size; memcpy(bn[0].data, sdo.data.pub_key.n.value, sdo.data.pub_key.n.size); bn[1].data = (unsigned char *) malloc(sdo.data.pub_key.e.size); if (!bn[1].data) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate exponent"); bn[1].len = sdo.data.pub_key.e.size; memcpy(bn[1].data, sdo.data.pub_key.e.value, sdo.data.pub_key.e.size); rsa_key.modulus = bn[0]; rsa_key.exponent = bn[1]; rv = sc_pkcs15_encode_pubkey_rsa(ctx, &rsa_key, out, out_len); LOG_TEST_RET(ctx, rv, "failed to read public key: cannot encode RSA public key"); if (out && out_len) sc_log(ctx, "encoded public key: %s", sc_dump_hex(*out, *out_len)); if (bn[0].data) free(bn[0].data); if (bn[1].data) free(bn[1].data); iasecc_sdo_free_fields(card, &sdo); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data) { struct sc_context *ctx = card->ctx; struct iasecc_sdo *sdo = NULL; int idx, rv; LOG_FUNC_CALLED(ctx); if ((ctl_data->key_size % 0x40) || ctl_data->index < 1 || (ctl_data->index > IASECC_OBJECT_REF_MAX)) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "get reference for key(index:%i,usage:%X,access:%X)", ctl_data->index, ctl_data->usage, ctl_data->access); /* TODO: when looking for the slot for the signature keys, check also PSO_SIGNATURE ACL */ for (idx = ctl_data->index; idx <= IASECC_OBJECT_REF_MAX; idx++) { unsigned char sdo_tag[3] = { IASECC_SDO_TAG_HEADER, IASECC_OBJECT_REF_LOCAL | IASECC_SDO_CLASS_RSA_PRIVATE, idx }; size_t sz; if (sdo) iasecc_sdo_free(card, sdo); rv = iasecc_sdo_allocate_and_parse(card, sdo_tag, 3, &sdo); LOG_TEST_RET(ctx, rv, "cannot parse SDO data"); rv = iasecc_sdo_get_data(card, sdo); if (rv == SC_ERROR_DATA_OBJECT_NOT_FOUND) { iasecc_sdo_free(card, sdo); sc_log(ctx, "found empty key slot %i", idx); break; } else LOG_TEST_RET(ctx, rv, "get new key reference failed"); sz = *(sdo->docp.size.value + 0) * 0x100 + *(sdo->docp.size.value + 1); sc_log(ctx, "SDO(idx:%i) size %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u", idx, sz, ctl_data->key_size); if (sz != ctl_data->key_size / 8) { sc_log(ctx, "key index %i ignored: different key sizes %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", idx, sz, ctl_data->key_size / 8); continue; } if (sdo->docp.non_repudiation.value) { sc_log(ctx, "non repudiation flag %X", sdo->docp.non_repudiation.value[0]); if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && !(*sdo->docp.non_repudiation.value)) { sc_log(ctx, "key index %i ignored: need non repudiation", idx); continue; } if (!(ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && *sdo->docp.non_repudiation.value) { sc_log(ctx, "key index %i ignored: don't need non-repudiation", idx); continue; } } if (ctl_data->access & SC_PKCS15_PRKEY_ACCESS_LOCAL) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: GENERATE KEY not allowed", idx); continue; } } else { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: PUT DATA not allowed", idx); continue; } } if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN)) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_SIGN] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: PSO SIGN not allowed", idx); continue; } } else if (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_INTERNAL_AUTH] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: INTERNAL AUTHENTICATE not allowed", idx); continue; } } if (ctl_data->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP)) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_DECIPHER] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: PSO DECIPHER not allowed", idx); continue; } } break; } ctl_data->index = idx; if (idx > IASECC_OBJECT_REF_MAX) LOG_FUNC_RETURN(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (!iso_ops) iso_ops = iso_drv->ops; iasecc_ops = *iso_ops; iasecc_ops.match_card = iasecc_match_card; iasecc_ops.init = iasecc_init; iasecc_ops.finish = iasecc_finish; iasecc_ops.read_binary = iasecc_read_binary; /* write_binary: ISO7816 implementation works */ /* update_binary: ISO7816 implementation works */ iasecc_ops.erase_binary = iasecc_erase_binary; /* resize_binary */ /* read_record: Untested */ /* write_record: Untested */ /* append_record: Untested */ /* update_record: Untested */ iasecc_ops.select_file = iasecc_select_file; /* get_response: Untested */ /* get_challenge: ISO7816 implementation works */ iasecc_ops.logout = iasecc_logout; /* restore_security_env */ iasecc_ops.set_security_env = iasecc_set_security_env; iasecc_ops.decipher = iasecc_decipher; iasecc_ops.compute_signature = iasecc_compute_signature; iasecc_ops.create_file = iasecc_create_file; iasecc_ops.delete_file = iasecc_delete_file; /* list_files */ iasecc_ops.check_sw = iasecc_check_sw; iasecc_ops.card_ctl = iasecc_card_ctl; iasecc_ops.process_fci = iasecc_process_fci; /* construct_fci: Not needed */ iasecc_ops.pin_cmd = iasecc_pin_cmd; /* get_data: Not implemented */ /* put_data: Not implemented */ /* delete_record: Not implemented */ iasecc_ops.read_public_key = iasecc_read_public_key; return &iasecc_drv; } struct sc_card_driver * sc_get_iasecc_driver(void) { return sc_get_driver(); } #else /* we need to define the functions below to export them */ #include "errors.h" int iasecc_se_get_info() { return SC_ERROR_NOT_SUPPORTED; } #endif /* ENABLE_OPENSSL */
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_8
crossvul-cpp_data_bad_2645_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Network File System (NFS) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "nfs.h" #include "nfsfh.h" #include "ip.h" #include "ip6.h" #include "rpc_auth.h" #include "rpc_msg.h" static const char tstr[] = " [|nfs]"; static void nfs_printfh(netdissect_options *, const uint32_t *, const u_int); static int xid_map_enter(netdissect_options *, const struct sunrpc_msg *, const u_char *); static int xid_map_find(const struct sunrpc_msg *, const u_char *, uint32_t *, uint32_t *); static void interp_reply(netdissect_options *, const struct sunrpc_msg *, uint32_t, uint32_t, int); static const uint32_t *parse_post_op_attr(netdissect_options *, const uint32_t *, int); /* * Mapping of old NFS Version 2 RPC numbers to generic numbers. */ static uint32_t nfsv3_procid[NFS_NPROCS] = { NFSPROC_NULL, NFSPROC_GETATTR, NFSPROC_SETATTR, NFSPROC_NOOP, NFSPROC_LOOKUP, NFSPROC_READLINK, NFSPROC_READ, NFSPROC_NOOP, NFSPROC_WRITE, NFSPROC_CREATE, NFSPROC_REMOVE, NFSPROC_RENAME, NFSPROC_LINK, NFSPROC_SYMLINK, NFSPROC_MKDIR, NFSPROC_RMDIR, NFSPROC_READDIR, NFSPROC_FSSTAT, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP }; static const struct tok nfsproc_str[] = { { NFSPROC_NOOP, "nop" }, { NFSPROC_NULL, "null" }, { NFSPROC_GETATTR, "getattr" }, { NFSPROC_SETATTR, "setattr" }, { NFSPROC_LOOKUP, "lookup" }, { NFSPROC_ACCESS, "access" }, { NFSPROC_READLINK, "readlink" }, { NFSPROC_READ, "read" }, { NFSPROC_WRITE, "write" }, { NFSPROC_CREATE, "create" }, { NFSPROC_MKDIR, "mkdir" }, { NFSPROC_SYMLINK, "symlink" }, { NFSPROC_MKNOD, "mknod" }, { NFSPROC_REMOVE, "remove" }, { NFSPROC_RMDIR, "rmdir" }, { NFSPROC_RENAME, "rename" }, { NFSPROC_LINK, "link" }, { NFSPROC_READDIR, "readdir" }, { NFSPROC_READDIRPLUS, "readdirplus" }, { NFSPROC_FSSTAT, "fsstat" }, { NFSPROC_FSINFO, "fsinfo" }, { NFSPROC_PATHCONF, "pathconf" }, { NFSPROC_COMMIT, "commit" }, { 0, NULL } }; /* * NFS V2 and V3 status values. * * Some of these come from the RFCs for NFS V2 and V3, with the message * strings taken from the FreeBSD C library "errlst.c". * * Others are errors that are not in the RFC but that I suspect some * NFS servers could return; the values are FreeBSD errno values, as * the first NFS server was the SunOS 2.0 one, and until 5.0 SunOS * was primarily BSD-derived. */ static const struct tok status2str[] = { { 1, "Operation not permitted" }, /* EPERM */ { 2, "No such file or directory" }, /* ENOENT */ { 5, "Input/output error" }, /* EIO */ { 6, "Device not configured" }, /* ENXIO */ { 11, "Resource deadlock avoided" }, /* EDEADLK */ { 12, "Cannot allocate memory" }, /* ENOMEM */ { 13, "Permission denied" }, /* EACCES */ { 17, "File exists" }, /* EEXIST */ { 18, "Cross-device link" }, /* EXDEV */ { 19, "Operation not supported by device" }, /* ENODEV */ { 20, "Not a directory" }, /* ENOTDIR */ { 21, "Is a directory" }, /* EISDIR */ { 22, "Invalid argument" }, /* EINVAL */ { 26, "Text file busy" }, /* ETXTBSY */ { 27, "File too large" }, /* EFBIG */ { 28, "No space left on device" }, /* ENOSPC */ { 30, "Read-only file system" }, /* EROFS */ { 31, "Too many links" }, /* EMLINK */ { 45, "Operation not supported" }, /* EOPNOTSUPP */ { 62, "Too many levels of symbolic links" }, /* ELOOP */ { 63, "File name too long" }, /* ENAMETOOLONG */ { 66, "Directory not empty" }, /* ENOTEMPTY */ { 69, "Disc quota exceeded" }, /* EDQUOT */ { 70, "Stale NFS file handle" }, /* ESTALE */ { 71, "Too many levels of remote in path" }, /* EREMOTE */ { 99, "Write cache flushed to disk" }, /* NFSERR_WFLUSH (not used) */ { 10001, "Illegal NFS file handle" }, /* NFS3ERR_BADHANDLE */ { 10002, "Update synchronization mismatch" }, /* NFS3ERR_NOT_SYNC */ { 10003, "READDIR/READDIRPLUS cookie is stale" }, /* NFS3ERR_BAD_COOKIE */ { 10004, "Operation not supported" }, /* NFS3ERR_NOTSUPP */ { 10005, "Buffer or request is too small" }, /* NFS3ERR_TOOSMALL */ { 10006, "Unspecified error on server" }, /* NFS3ERR_SERVERFAULT */ { 10007, "Object of that type not supported" }, /* NFS3ERR_BADTYPE */ { 10008, "Request couldn't be completed in time" }, /* NFS3ERR_JUKEBOX */ { 0, NULL } }; static const struct tok nfsv3_writemodes[] = { { 0, "unstable" }, { 1, "datasync" }, { 2, "filesync" }, { 0, NULL } }; static const struct tok type2str[] = { { NFNON, "NON" }, { NFREG, "REG" }, { NFDIR, "DIR" }, { NFBLK, "BLK" }, { NFCHR, "CHR" }, { NFLNK, "LNK" }, { NFFIFO, "FIFO" }, { 0, NULL } }; static const struct tok sunrpc_auth_str[] = { { SUNRPC_AUTH_OK, "OK" }, { SUNRPC_AUTH_BADCRED, "Bogus Credentials (seal broken)" }, { SUNRPC_AUTH_REJECTEDCRED, "Rejected Credentials (client should begin new session)" }, { SUNRPC_AUTH_BADVERF, "Bogus Verifier (seal broken)" }, { SUNRPC_AUTH_REJECTEDVERF, "Verifier expired or was replayed" }, { SUNRPC_AUTH_TOOWEAK, "Credentials are too weak" }, { SUNRPC_AUTH_INVALIDRESP, "Bogus response verifier" }, { SUNRPC_AUTH_FAILED, "Unknown failure" }, { 0, NULL } }; static const struct tok sunrpc_str[] = { { SUNRPC_PROG_UNAVAIL, "PROG_UNAVAIL" }, { SUNRPC_PROG_MISMATCH, "PROG_MISMATCH" }, { SUNRPC_PROC_UNAVAIL, "PROC_UNAVAIL" }, { SUNRPC_GARBAGE_ARGS, "GARBAGE_ARGS" }, { SUNRPC_SYSTEM_ERR, "SYSTEM_ERR" }, { 0, NULL } }; static void print_nfsaddr(netdissect_options *ndo, const u_char *bp, const char *s, const char *d) { const struct ip *ip; const struct ip6_hdr *ip6; char srcaddr[INET6_ADDRSTRLEN], dstaddr[INET6_ADDRSTRLEN]; srcaddr[0] = dstaddr[0] = '\0'; switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; strlcpy(srcaddr, ipaddr_string(ndo, &ip->ip_src), sizeof(srcaddr)); strlcpy(dstaddr, ipaddr_string(ndo, &ip->ip_dst), sizeof(dstaddr)); break; case 6: ip6 = (const struct ip6_hdr *)bp; strlcpy(srcaddr, ip6addr_string(ndo, &ip6->ip6_src), sizeof(srcaddr)); strlcpy(dstaddr, ip6addr_string(ndo, &ip6->ip6_dst), sizeof(dstaddr)); break; default: strlcpy(srcaddr, "?", sizeof(srcaddr)); strlcpy(dstaddr, "?", sizeof(dstaddr)); break; } ND_PRINT((ndo, "%s.%s > %s.%s: ", srcaddr, s, dstaddr, d)); } static const uint32_t * parse_sattr3(netdissect_options *ndo, const uint32_t *dp, struct nfsv3_sattr *sa3) { ND_TCHECK(dp[0]); sa3->sa_modeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_modeset) { ND_TCHECK(dp[0]); sa3->sa_mode = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_uidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_uidset) { ND_TCHECK(dp[0]); sa3->sa_uid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_gidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_gidset) { ND_TCHECK(dp[0]); sa3->sa_gid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_sizeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_sizeset) { ND_TCHECK(dp[0]); sa3->sa_size = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_atimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_atime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_atime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_mtimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_mtime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_mtime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } return dp; trunc: return NULL; } static int nfserr; /* true if we error rather than trunc */ static void print_sattr3(netdissect_options *ndo, const struct nfsv3_sattr *sa3, int verbose) { if (sa3->sa_modeset) ND_PRINT((ndo, " mode %o", sa3->sa_mode)); if (sa3->sa_uidset) ND_PRINT((ndo, " uid %u", sa3->sa_uid)); if (sa3->sa_gidset) ND_PRINT((ndo, " gid %u", sa3->sa_gid)); if (verbose > 1) { if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " atime %u.%06u", sa3->sa_atime.nfsv3_sec, sa3->sa_atime.nfsv3_nsec)); if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " mtime %u.%06u", sa3->sa_mtime.nfsv3_sec, sa3->sa_mtime.nfsv3_nsec)); } } void nfsreply_print(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; char srcid[20], dstid[20]; /*fits 32bit*/ nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_xid); if (!ndo->ndo_nflag) { strlcpy(srcid, "nfs", sizeof(srcid)); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } else { snprintf(srcid, sizeof(srcid), "%u", NFS_PORT); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } print_nfsaddr(ndo, bp2, srcid, dstid); nfsreply_print_noaddr(ndo, bp, length, bp2); return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } void nfsreply_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; uint32_t proc, vers, reply_stat; enum sunrpc_reject_stat rstat; uint32_t rlow; uint32_t rhigh; enum sunrpc_auth_stat rwhy; nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_reply.rp_stat); reply_stat = EXTRACT_32BITS(&rp->rm_reply.rp_stat); switch (reply_stat) { case SUNRPC_MSG_ACCEPTED: ND_PRINT((ndo, "reply ok %u", length)); if (xid_map_find(rp, bp2, &proc, &vers) >= 0) interp_reply(ndo, rp, proc, vers, length); break; case SUNRPC_MSG_DENIED: ND_PRINT((ndo, "reply ERR %u: ", length)); ND_TCHECK(rp->rm_reply.rp_reject.rj_stat); rstat = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_stat); switch (rstat) { case SUNRPC_RPC_MISMATCH: ND_TCHECK(rp->rm_reply.rp_reject.rj_vers.high); rlow = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.low); rhigh = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.high); ND_PRINT((ndo, "RPC Version mismatch (%u-%u)", rlow, rhigh)); break; case SUNRPC_AUTH_ERROR: ND_TCHECK(rp->rm_reply.rp_reject.rj_why); rwhy = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_why); ND_PRINT((ndo, "Auth %s", tok2str(sunrpc_auth_str, "Invalid failure code %u", rwhy))); break; default: ND_PRINT((ndo, "Unknown reason for rejecting rpc message %u", (unsigned int)rstat)); break; } break; default: ND_PRINT((ndo, "reply Unknown rpc response code=%u %u", reply_stat, length)); break; } return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Return a pointer to the first file handle in the packet. * If the packet was truncated, return 0. */ static const uint32_t * parsereq(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; register u_int len; /* * find the start of the req data (if we captured it) */ dp = (const uint32_t *)&rp->rm_call.cb_cred; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK2(dp[0], 0); return (dp); } } trunc: return (NULL); } /* * Print out an NFS file handle and return a pointer to following word. * If packet was truncated, return 0. */ static const uint32_t * parsefh(netdissect_options *ndo, register const uint32_t *dp, int v3) { u_int len; if (v3) { ND_TCHECK(dp[0]); len = EXTRACT_32BITS(dp) / 4; dp++; } else len = NFSX_V2FH / 4; if (ND_TTEST2(*dp, len * sizeof(*dp))) { nfs_printfh(ndo, dp, len); return (dp + len); } trunc: return (NULL); } /* * Print out a file name and return pointer to 32-bit word past it. * If packet was truncated, return 0. */ static const uint32_t * parsefn(netdissect_options *ndo, register const uint32_t *dp) { register uint32_t len; register const u_char *cp; /* Bail if we don't have the string length */ ND_TCHECK(*dp); /* Fetch string length; convert to host order */ len = *dp++; NTOHL(len); ND_TCHECK2(*dp, ((len + 3) & ~3)); cp = (const u_char *)dp; /* Update 32-bit pointer (NFS filenames padded to 32-bit boundaries) */ dp += ((len + 3) & ~3) / sizeof(*dp); ND_PRINT((ndo, "\"")); if (fn_printn(ndo, cp, len, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); return (dp); trunc: return NULL; } /* * Print out file handle and file name. * Return pointer to 32-bit word past file name. * If packet was truncated (or there was some other error), return 0. */ static const uint32_t * parsefhn(netdissect_options *ndo, register const uint32_t *dp, int v3) { dp = parsefh(ndo, dp, v3); if (dp == NULL) return (NULL); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp)); } void nfsreq_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; register const uint32_t *dp; nfs_type type; int v3; uint32_t proc; uint32_t access_flags; struct nfsv3_sattr sa3; ND_PRINT((ndo, "%d", length)); nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */ goto trunc; v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3); proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: case NFSPROC_SETATTR: case NFSPROC_READLINK: case NFSPROC_FSSTAT: case NFSPROC_FSINFO: case NFSPROC_PATHCONF: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefh(ndo, dp, v3) != NULL) return; break; case NFSPROC_LOOKUP: case NFSPROC_CREATE: case NFSPROC_MKDIR: case NFSPROC_REMOVE: case NFSPROC_RMDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefhn(ndo, dp, v3) != NULL) return; break; case NFSPROC_ACCESS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[0]); access_flags = EXTRACT_32BITS(&dp[0]); if (access_flags & ~NFSV3ACCESS_FULL) { /* NFSV3ACCESS definitions aren't up to date */ ND_PRINT((ndo, " %04x", access_flags)); } else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) { ND_PRINT((ndo, " NFS_ACCESS_FULL")); } else { char separator = ' '; if (access_flags & NFSV3ACCESS_READ) { ND_PRINT((ndo, " NFS_ACCESS_READ")); separator = '|'; } if (access_flags & NFSV3ACCESS_LOOKUP) { ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_MODIFY) { ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXTEND) { ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_DELETE) { ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXECUTE) ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator)); } return; } break; case NFSPROC_READ: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); } else { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes @ %u", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_WRITE: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64, EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { dp += 3; ND_TCHECK(dp[0]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(dp)))); } } else { ND_TCHECK(dp[3]); ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)", EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_SYMLINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; if (parsefn(ndo, dp) == NULL) break; if (v3 && ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_MKNOD: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_TCHECK(*dp); type = (nfs_type)EXTRACT_32BITS(dp); dp++; if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type))); if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u/%u", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); dp += 2; } if (ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_RENAME: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_LINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_READDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); /* * We shouldn't really try to interpret the * offset cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3])); } else { ND_TCHECK(dp[1]); /* * Print the offset as signed, since -1 is * common, but offsets > 2^31 aren't. */ ND_PRINT((ndo, " %u bytes @ %d", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_READDIRPLUS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[4]); /* * We don't try to interpret the offset * cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_TCHECK(dp[5]); ND_PRINT((ndo, " max %u verf %08x%08x", EXTRACT_32BITS(&dp[5]), dp[2], dp[3])); } return; } break; case NFSPROC_COMMIT: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); return; } break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Print out an NFS file handle. * We assume packet was not truncated before the end of the * file handle pointed to by dp. * * Note: new version (using portable file-handle parser) doesn't produce * generation number. It probably could be made to do that, with some * additional hacking on the parser code. */ static void nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ static char temp[NFSX_V3FHMAX+1]; /* Make sure string is null-terminated */ strncpy(temp, sfsname, NFSX_V3FHMAX); temp[sizeof(temp) - 1] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); } /* * Maintain a small cache of recent client.XID.server/proc pairs, to allow * us to match up replies with requests and thus to know how to parse * the reply. */ struct xid_map_entry { uint32_t xid; /* transaction ID (net order) */ int ipver; /* IP version (4 or 6) */ struct in6_addr client; /* client IP address (net order) */ struct in6_addr server; /* server IP address (net order) */ uint32_t proc; /* call proc number (host order) */ uint32_t vers; /* program version (host order) */ }; /* * Map entries are kept in an array that we manage as a ring; * new entries are always added at the tail of the ring. Initially, * all the entries are zero and hence don't match anything. */ #define XIDMAPSIZE 64 static struct xid_map_entry xid_map[XIDMAPSIZE]; static int xid_map_next = 0; static int xid_map_hint = 0; static int xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } /* * Returns 0 and puts NFSPROC_xxx in proc return and * version in vers return, or returns -1 on failure */ static int xid_map_find(const struct sunrpc_msg *rp, const u_char *bp, uint32_t *proc, uint32_t *vers) { int i; struct xid_map_entry *xmep; uint32_t xid; const struct ip *ip = (const struct ip *)bp; const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp; int cmp; UNALIGNED_MEMCPY(&xid, &rp->rm_xid, sizeof(xmep->xid)); /* Start searching from where we last left off */ i = xid_map_hint; do { xmep = &xid_map[i]; cmp = 1; if (xmep->ipver != IP_V(ip) || xmep->xid != xid) goto nextitem; switch (xmep->ipver) { case 4: if (UNALIGNED_MEMCMP(&ip->ip_src, &xmep->server, sizeof(ip->ip_src)) != 0 || UNALIGNED_MEMCMP(&ip->ip_dst, &xmep->client, sizeof(ip->ip_dst)) != 0) { cmp = 0; } break; case 6: if (UNALIGNED_MEMCMP(&ip6->ip6_src, &xmep->server, sizeof(ip6->ip6_src)) != 0 || UNALIGNED_MEMCMP(&ip6->ip6_dst, &xmep->client, sizeof(ip6->ip6_dst)) != 0) { cmp = 0; } break; default: cmp = 0; break; } if (cmp) { /* match */ xid_map_hint = i; *proc = xmep->proc; *vers = xmep->vers; return 0; } nextitem: if (++i >= XIDMAPSIZE) i = 0; } while (i != xid_map_hint); /* search failed */ return (-1); } /* * Routines for parsing reply packets */ /* * Return a pointer to the beginning of the actual results. * If the packet was truncated, return 0. */ static const uint32_t * parserep(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; u_int len; enum sunrpc_accept_stat astat; /* * Portability note: * Here we find the address of the ar_verf credentials. * Originally, this calculation was * dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf * On the wire, the rp_acpt field starts immediately after * the (32 bit) rp_stat field. However, rp_acpt (which is a * "struct accepted_reply") contains a "struct opaque_auth", * whose internal representation contains a pointer, so on a * 64-bit machine the compiler inserts 32 bits of padding * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use * the internal representation to parse the on-the-wire * representation. Instead, we skip past the rp_stat field, * which is an "enum" and so occupies one 32-bit word. */ dp = ((const uint32_t *)&rp->rm_reply) + 1; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len >= length) return (NULL); /* * skip past the ar_verf credentials. */ dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t); ND_TCHECK2(dp[0], 0); /* * now we can check the ar_stat field */ astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp); if (astat != SUNRPC_SUCCESS) { ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat))); nfserr = 1; /* suppress trunc string */ return (NULL); } /* successful return */ ND_TCHECK2(*dp, sizeof(astat)); return ((const uint32_t *) (sizeof(astat) + ((const char *)dp))); trunc: return (0); } static const uint32_t * parsestatus(netdissect_options *ndo, const uint32_t *dp, int *er) { int errnum; ND_TCHECK(dp[0]); errnum = EXTRACT_32BITS(&dp[0]); if (er) *er = errnum; if (errnum != 0) { if (!ndo->ndo_qflag) ND_PRINT((ndo, " ERROR: %s", tok2str(status2str, "unk %d", errnum))); nfserr = 1; } return (dp + 1); trunc: return NULL; } static const uint32_t * parsefattr(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { const struct nfs_fattr *fap; fap = (const struct nfs_fattr *)dp; ND_TCHECK(fap->fa_gid); if (verbose) { ND_PRINT((ndo, " %s %o ids %d/%d", tok2str(type2str, "unk-ft %d ", EXTRACT_32BITS(&fap->fa_type)), EXTRACT_32BITS(&fap->fa_mode), EXTRACT_32BITS(&fap->fa_uid), EXTRACT_32BITS(&fap->fa_gid))); if (v3) { ND_TCHECK(fap->fa3_size); ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_size))); } else { ND_TCHECK(fap->fa2_size); ND_PRINT((ndo, " sz %d", EXTRACT_32BITS(&fap->fa2_size))); } } /* print lots more stuff */ if (verbose > 1) { if (v3) { ND_TCHECK(fap->fa3_ctime); ND_PRINT((ndo, " nlink %d rdev %d/%d", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa3_rdev.specdata1), EXTRACT_32BITS(&fap->fa3_rdev.specdata2))); ND_PRINT((ndo, " fsid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fsid))); ND_PRINT((ndo, " fileid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fileid))); ND_PRINT((ndo, " a/m/ctime %u.%06u", EXTRACT_32BITS(&fap->fa3_atime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_atime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_nsec))); } else { ND_TCHECK(fap->fa2_ctime); ND_PRINT((ndo, " nlink %d rdev 0x%x fsid 0x%x nodeid 0x%x a/m/ctime", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa2_rdev), EXTRACT_32BITS(&fap->fa2_fsid), EXTRACT_32BITS(&fap->fa2_fileid))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_atime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_atime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_usec))); } } return ((const uint32_t *)((const unsigned char *)dp + (v3 ? NFSX_V3FATTR : NFSX_V2FATTR))); trunc: return (NULL); } static int parseattrstat(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); return (parsefattr(ndo, dp, verbose, v3) != NULL); } static int parsediropres(netdissect_options *ndo, const uint32_t *dp) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) return (1); dp = parsefh(ndo, dp, 0); if (dp == NULL) return (0); return (parsefattr(ndo, dp, ndo->ndo_vflag, 0) != NULL); } static int parselinkres(netdissect_options *ndo, const uint32_t *dp, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return(0); if (er) return(1); if (v3 && !(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp) != NULL); } static int parsestatfs(netdissect_options *ndo, const uint32_t *dp, int v3) { const struct nfs_statfs *sfsp; int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (!v3 && er) return (1); if (ndo->ndo_qflag) return(1); if (v3) { if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); } ND_TCHECK2(*dp, (v3 ? NFSX_V3STATFS : NFSX_V2STATFS)); sfsp = (const struct nfs_statfs *)dp; if (v3) { ND_PRINT((ndo, " tbytes %" PRIu64 " fbytes %" PRIu64 " abytes %" PRIu64, EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_fbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_abytes))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " tfiles %" PRIu64 " ffiles %" PRIu64 " afiles %" PRIu64 " invar %u", EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tfiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_ffiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_afiles), EXTRACT_32BITS(&sfsp->sf_invarsec))); } } else { ND_PRINT((ndo, " tsize %d bsize %d blocks %d bfree %d bavail %d", EXTRACT_32BITS(&sfsp->sf_tsize), EXTRACT_32BITS(&sfsp->sf_bsize), EXTRACT_32BITS(&sfsp->sf_blocks), EXTRACT_32BITS(&sfsp->sf_bfree), EXTRACT_32BITS(&sfsp->sf_bavail))); } return (1); trunc: return (0); } static int parserddires(netdissect_options *ndo, const uint32_t *dp) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); if (ndo->ndo_qflag) return (1); ND_TCHECK(dp[2]); ND_PRINT((ndo, " offset 0x%x size %d ", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); if (dp[2] != 0) ND_PRINT((ndo, " eof")); return (1); trunc: return (0); } static const uint32_t * parse_wcc_attr(netdissect_options *ndo, const uint32_t *dp) { ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0]))); ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u", EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5]))); return (dp + 6); } /* * Pre operation attributes. Print only if vflag > 1. */ static const uint32_t * parse_pre_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; ND_TCHECK2(*dp, 24); if (verbose > 1) { return parse_wcc_attr(ndo, dp); } else { /* If not verbose enough, just skip over wcc_attr */ return (dp + 6); } trunc: return (NULL); } /* * Post operation attributes are printed if vflag >= 1 */ static const uint32_t * parse_post_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (verbose) { return parsefattr(ndo, dp, verbose, 1); } else return (dp + (NFSX_V3FATTR / sizeof (uint32_t))); trunc: return (NULL); } static const uint32_t * parse_wcc_data(netdissect_options *ndo, const uint32_t *dp, int verbose) { if (verbose > 1) ND_PRINT((ndo, " PRE:")); if (!(dp = parse_pre_op_attr(ndo, dp, verbose))) return (0); if (verbose) ND_PRINT((ndo, " POST:")); return parse_post_op_attr(ndo, dp, verbose); } static const uint32_t * parsecreateopres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) dp = parse_wcc_data(ndo, dp, verbose); else { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (!(dp = parsefh(ndo, dp, 1))) return (0); if (verbose) { if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " dir attr:")); dp = parse_wcc_data(ndo, dp, verbose); } } } return (dp); trunc: return (NULL); } static int parsewccres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); return parse_wcc_data(ndo, dp, verbose) != NULL; } static const uint32_t * parsev3rddirres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (er) return dp; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " verf %08x%08x", dp[0], dp[1])); dp += 2; } return dp; trunc: return (NULL); } static int parsefsinfo(netdissect_options *ndo, const uint32_t *dp) { const struct nfsv3_fsinfo *sfp; int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); sfp = (const struct nfsv3_fsinfo *)dp; ND_TCHECK(*sfp); ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u", EXTRACT_32BITS(&sfp->fs_rtmax), EXTRACT_32BITS(&sfp->fs_rtpref), EXTRACT_32BITS(&sfp->fs_wtmax), EXTRACT_32BITS(&sfp->fs_wtpref), EXTRACT_32BITS(&sfp->fs_dtpref))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64, EXTRACT_32BITS(&sfp->fs_rtmult), EXTRACT_32BITS(&sfp->fs_wtmult), EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize))); ND_PRINT((ndo, " delta %u.%06u ", EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec), EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec))); } return (1); trunc: return (0); } static int parsepathconf(netdissect_options *ndo, const uint32_t *dp) { int er; const struct nfsv3_pathconf *spp; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); spp = (const struct nfsv3_pathconf *)dp; ND_TCHECK(*spp); ND_PRINT((ndo, " linkmax %u namemax %u %s %s %s %s", EXTRACT_32BITS(&spp->pc_linkmax), EXTRACT_32BITS(&spp->pc_namemax), EXTRACT_32BITS(&spp->pc_notrunc) ? "notrunc" : "", EXTRACT_32BITS(&spp->pc_chownrestricted) ? "chownres" : "", EXTRACT_32BITS(&spp->pc_caseinsensitive) ? "igncase" : "", EXTRACT_32BITS(&spp->pc_casepreserving) ? "keepcase" : "")); return (1); trunc: return (0); } static void interp_reply(netdissect_options *ndo, const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length) { register const uint32_t *dp; register int v3; int er; v3 = (vers == NFS_VER3); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: dp = parserep(ndo, rp, length); if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0) return; break; case NFSPROC_SETATTR: if (!(dp = parserep(ndo, rp, length))) return; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0) return; } break; case NFSPROC_LOOKUP: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (er) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } else { if (!(dp = parsefh(ndo, dp, v3))) break; if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) && ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } if (dp) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_ACCESS: if (!(dp = parserep(ndo, rp, length))) break; if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) ND_PRINT((ndo, " attr:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (!er) ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0]))); return; case NFSPROC_READLINK: dp = parserep(ndo, rp, length); if (dp != NULL && parselinkres(ndo, dp, v3) != 0) return; break; case NFSPROC_READ: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (EXTRACT_32BITS(&dp[1])) ND_PRINT((ndo, " EOF")); } return; } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0) return; } break; case NFSPROC_WRITE: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (ndo->ndo_vflag > 1) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[1])))); } return; } } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0) return; } break; case NFSPROC_CREATE: case NFSPROC_MKDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_SYMLINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_MKNOD: if (!(dp = parserep(ndo, rp, length))) break; if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; break; case NFSPROC_REMOVE: case NFSPROC_RMDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_RENAME: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " from:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " to:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; } return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_LINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " file POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " dir:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; return; } } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_READDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parserddires(ndo, dp) != 0) return; } break; case NFSPROC_READDIRPLUS: if (!(dp = parserep(ndo, rp, length))) break; if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; break; case NFSPROC_FSSTAT: dp = parserep(ndo, rp, length); if (dp != NULL && parsestatfs(ndo, dp, v3) != 0) return; break; case NFSPROC_FSINFO: dp = parserep(ndo, rp, length); if (dp != NULL && parsefsinfo(ndo, dp) != 0) return; break; case NFSPROC_PATHCONF: dp = parserep(ndo, rp, length); if (dp != NULL && parsepathconf(ndo, dp) != 0) return; break; case NFSPROC_COMMIT: dp = parserep(ndo, rp, length); if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0) return; break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2645_0
crossvul-cpp_data_bad_2689_0
/* * Copyright (c) 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: White Board printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" static const char tstr[] = "[|wb]"; /* XXX need to add byte-swapping macros! */ /* XXX - you mean like the ones in "extract.h"? */ /* * Largest packet size. Everything should fit within this space. * For instance, multiline objects are sent piecewise. */ #define MAXFRAMESIZE 1024 /* * Multiple drawing ops can be sent in one packet. Each one starts on a * an even multiple of DOP_ALIGN bytes, which must be a power of two. */ #define DOP_ALIGN 4 #define DOP_ROUNDUP(x) ((((int)(x)) + (DOP_ALIGN - 1)) & ~(DOP_ALIGN - 1)) #define DOP_NEXT(d)\ ((const struct dophdr *)((const u_char *)(d) + \ DOP_ROUNDUP(EXTRACT_16BITS(&(d)->dh_len) + sizeof(*(d))))) /* * Format of the whiteboard packet header. * The transport level header. */ struct pkt_hdr { uint32_t ph_src; /* site id of source */ uint32_t ph_ts; /* time stamp (for skew computation) */ uint16_t ph_version; /* version number */ u_char ph_type; /* message type */ u_char ph_flags; /* message flags */ }; /* Packet types */ #define PT_DRAWOP 0 /* drawing operation */ #define PT_ID 1 /* announcement packet */ #define PT_RREQ 2 /* repair request */ #define PT_RREP 3 /* repair reply */ #define PT_KILL 4 /* terminate participation */ #define PT_PREQ 5 /* page vector request */ #define PT_PREP 7 /* page vector reply */ #ifdef PF_USER #undef PF_USER /* {Digital,Tru64} UNIX define this, alas */ #endif /* flags */ #define PF_USER 0x01 /* hint that packet has interactive data */ #define PF_VIS 0x02 /* only visible ops wanted */ struct PageID { uint32_t p_sid; /* session id of initiator */ uint32_t p_uid; /* page number */ }; struct dophdr { uint32_t dh_ts; /* sender's timestamp */ uint16_t dh_len; /* body length */ u_char dh_flags; u_char dh_type; /* body type */ /* body follows */ }; /* * Drawing op sub-types. */ #define DT_RECT 2 #define DT_LINE 3 #define DT_ML 4 #define DT_DEL 5 #define DT_XFORM 6 #define DT_ELL 7 #define DT_CHAR 8 #define DT_STR 9 #define DT_NOP 10 #define DT_PSCODE 11 #define DT_PSCOMP 12 #define DT_REF 13 #define DT_SKIP 14 #define DT_HOLE 15 #define DT_MAXTYPE 15 /* * A drawing operation. */ struct pkt_dop { struct PageID pd_page; /* page that operations apply to */ uint32_t pd_sseq; /* start sequence number */ uint32_t pd_eseq; /* end sequence number */ /* drawing ops follow */ }; /* * A repair request. */ struct pkt_rreq { uint32_t pr_id; /* source id of drawops to be repaired */ struct PageID pr_page; /* page of drawops */ uint32_t pr_sseq; /* start seqno */ uint32_t pr_eseq; /* end seqno */ }; /* * A repair reply. */ struct pkt_rrep { uint32_t pr_id; /* original site id of ops */ struct pkt_dop pr_dop; /* drawing ops follow */ }; struct id_off { uint32_t id; uint32_t off; }; struct pgstate { uint32_t slot; struct PageID page; uint16_t nid; uint16_t rsvd; /* seqptr's */ }; /* * An announcement packet. */ struct pkt_id { uint32_t pi_mslot; struct PageID pi_mpage; /* current page */ struct pgstate pi_ps; /* seqptr's */ /* null-terminated site name */ }; struct pkt_preq { struct PageID pp_page; uint32_t pp_low; uint32_t pp_high; }; struct pkt_prep { uint32_t pp_n; /* size of pageid array */ /* pgstate's follow */ }; static int wb_id(netdissect_options *ndo, const struct pkt_id *id, u_int len) { int i; const char *cp; const struct id_off *io; char c; int nid; ND_PRINT((ndo, " wb-id:")); if (len < sizeof(*id) || !ND_TTEST(*id)) return (-1); len -= sizeof(*id); ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ", EXTRACT_32BITS(&id->pi_ps.slot), ipaddr_string(ndo, &id->pi_ps.page.p_sid), EXTRACT_32BITS(&id->pi_ps.page.p_uid), EXTRACT_32BITS(&id->pi_mslot), ipaddr_string(ndo, &id->pi_mpage.p_sid), EXTRACT_32BITS(&id->pi_mpage.p_uid))); nid = EXTRACT_16BITS(&id->pi_ps.nid); len -= sizeof(*io) * nid; io = (const struct id_off *)(id + 1); cp = (const char *)(io + nid); if (ND_TTEST2(cp, len)) { ND_PRINT((ndo, "\"")); fn_print(ndo, (const u_char *)cp, (const u_char *)cp + len); ND_PRINT((ndo, "\"")); } c = '<'; for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } if (i >= nid) { ND_PRINT((ndo, ">")); return (0); } return (-1); } static int wb_rreq(netdissect_options *ndo, const struct pkt_rreq *rreq, u_int len) { ND_PRINT((ndo, " wb-rreq:")); if (len < sizeof(*rreq) || !ND_TTEST(*rreq)) return (-1); ND_PRINT((ndo, " please repair %s %s:%u<%u:%u>", ipaddr_string(ndo, &rreq->pr_id), ipaddr_string(ndo, &rreq->pr_page.p_sid), EXTRACT_32BITS(&rreq->pr_page.p_uid), EXTRACT_32BITS(&rreq->pr_sseq), EXTRACT_32BITS(&rreq->pr_eseq))); return (0); } static int wb_preq(netdissect_options *ndo, const struct pkt_preq *preq, u_int len) { ND_PRINT((ndo, " wb-preq:")); if (len < sizeof(*preq) || !ND_TTEST(*preq)) return (-1); ND_PRINT((ndo, " need %u/%s:%u", EXTRACT_32BITS(&preq->pp_low), ipaddr_string(ndo, &preq->pp_page.p_sid), EXTRACT_32BITS(&preq->pp_page.p_uid))); return (0); } static int wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep)) { return (-1); } n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); } static const char *dopstr[] = { "dop-0!", "dop-1!", "RECT", "LINE", "ML", "DEL", "XFORM", "ELL", "CHAR", "STR", "NOP", "PSCODE", "PSCOMP", "REF", "SKIP", "HOLE", }; static int wb_dops(netdissect_options *ndo, const struct pkt_dop *dop, uint32_t ss, uint32_t es) { const struct dophdr *dh = (const struct dophdr *)((const u_char *)dop + sizeof(*dop)); ND_PRINT((ndo, " <")); for ( ; ss <= es; ++ss) { int t; if (!ND_TTEST(*dh)) { ND_PRINT((ndo, "%s", tstr)); break; } t = dh->dh_type; if (t > DT_MAXTYPE) ND_PRINT((ndo, " dop-%d!", t)); else { ND_PRINT((ndo, " %s", dopstr[t])); if (t == DT_SKIP || t == DT_HOLE) { uint32_t ts = EXTRACT_32BITS(&dh->dh_ts); ND_PRINT((ndo, "%d", ts - ss + 1)); if (ss > ts || ts > es) { ND_PRINT((ndo, "[|]")); if (ts < ss) return (0); } ss = ts; } } dh = DOP_NEXT(dh); } ND_PRINT((ndo, " >")); return (0); } static int wb_rrep(netdissect_options *ndo, const struct pkt_rrep *rrep, u_int len) { const struct pkt_dop *dop = &rrep->pr_dop; ND_PRINT((ndo, " wb-rrep:")); if (len < sizeof(*rrep) || !ND_TTEST(*rrep)) return (-1); len -= sizeof(*rrep); ND_PRINT((ndo, " for %s %s:%u<%u:%u>", ipaddr_string(ndo, &rrep->pr_id), ipaddr_string(ndo, &dop->pd_page.p_sid), EXTRACT_32BITS(&dop->pd_page.p_uid), EXTRACT_32BITS(&dop->pd_sseq), EXTRACT_32BITS(&dop->pd_eseq))); if (ndo->ndo_vflag) return (wb_dops(ndo, dop, EXTRACT_32BITS(&dop->pd_sseq), EXTRACT_32BITS(&dop->pd_eseq))); return (0); } static int wb_drawop(netdissect_options *ndo, const struct pkt_dop *dop, u_int len) { ND_PRINT((ndo, " wb-dop:")); if (len < sizeof(*dop) || !ND_TTEST(*dop)) return (-1); len -= sizeof(*dop); ND_PRINT((ndo, " %s:%u<%u:%u>", ipaddr_string(ndo, &dop->pd_page.p_sid), EXTRACT_32BITS(&dop->pd_page.p_uid), EXTRACT_32BITS(&dop->pd_sseq), EXTRACT_32BITS(&dop->pd_eseq))); if (ndo->ndo_vflag) return (wb_dops(ndo, dop, EXTRACT_32BITS(&dop->pd_sseq), EXTRACT_32BITS(&dop->pd_eseq))); return (0); } /* * Print whiteboard multicast packets. */ void wb_print(netdissect_options *ndo, register const void *hdr, register u_int len) { register const struct pkt_hdr *ph; ph = (const struct pkt_hdr *)hdr; if (len < sizeof(*ph) || !ND_TTEST(*ph)) { ND_PRINT((ndo, "%s", tstr)); return; } len -= sizeof(*ph); if (ph->ph_flags) ND_PRINT((ndo, "*")); switch (ph->ph_type) { case PT_KILL: ND_PRINT((ndo, " wb-kill")); return; case PT_ID: if (wb_id(ndo, (const struct pkt_id *)(ph + 1), len) >= 0) return; break; case PT_RREQ: if (wb_rreq(ndo, (const struct pkt_rreq *)(ph + 1), len) >= 0) return; break; case PT_RREP: if (wb_rrep(ndo, (const struct pkt_rrep *)(ph + 1), len) >= 0) return; break; case PT_DRAWOP: if (wb_drawop(ndo, (const struct pkt_dop *)(ph + 1), len) >= 0) return; break; case PT_PREQ: if (wb_preq(ndo, (const struct pkt_preq *)(ph + 1), len) >= 0) return; break; case PT_PREP: if (wb_prep(ndo, (const struct pkt_prep *)(ph + 1), len) >= 0) return; break; default: ND_PRINT((ndo, " wb-%d!", ph->ph_type)); return; } }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2689_0
crossvul-cpp_data_good_157_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/. * * ---------------------------------------------------------------------------- * This file is designed to be parsed during the build process * * Contains JavaScript Graphics Draw Functions * ---------------------------------------------------------------------------- */ #include "jswrap_graphics.h" #include "jsutils.h" #include "jsinteractive.h" #include "lcd_arraybuffer.h" #include "lcd_js.h" #ifdef USE_LCD_SDL #include "lcd_sdl.h" #endif #ifdef USE_LCD_FSMC #include "lcd_fsmc.h" #endif /*JSON{ "type" : "class", "class" : "Graphics" } This class provides Graphics operations that can be applied to a surface. Use Graphics.createXXX to create a graphics object that renders in the way you want. See [the Graphics page](/Graphics) for more information. **Note:** On boards that contain an LCD, there is a built-in 'LCD' object of type Graphics. For instance to draw a line you'd type: ```LCD.drawLine(0,0,100,100)``` */ /*JSON{ "type" : "idle", "generate" : "jswrap_graphics_idle" }*/ bool jswrap_graphics_idle() { graphicsIdle(); return false; } /*JSON{ "type" : "init", "generate" : "jswrap_graphics_init" }*/ void jswrap_graphics_init() { #ifdef USE_LCD_FSMC JsVar *parent = jspNewObject("LCD", "Graphics"); if (parent) { JsVar *parentObj = jsvSkipName(parent); JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_FSMC; gfx.graphicsVar = parentObj; gfx.data.width = 320; gfx.data.height = 240; gfx.data.bpp = 16; lcdInit_FSMC(&gfx); lcdSetCallbacks_FSMC(&gfx); graphicsSplash(&gfx); graphicsSetVar(&gfx); jsvUnLock2(parentObj, parent); } #endif } static bool isValidBPP(int bpp) { return bpp==1 || bpp==2 || bpp==4 || bpp==8 || bpp==16 || bpp==24 || bpp==32; // currently one colour can't ever be spread across multiple bytes } /*JSON{ "type" : "staticmethod", "class" : "Graphics", "name" : "createArrayBuffer", "generate" : "jswrap_graphics_createArrayBuffer", "params" : [ ["width","int32","Pixels wide"], ["height","int32","Pixels high"], ["bpp","int32","Number of bits per pixel"], ["options","JsVar",[ "An object of other options. ```{ zigzag : true/false(default), vertical_byte : true/false(default), msb : true/false(default), color_order: 'rgb'(default),'bgr',etc }```", "zigzag = whether to alternate the direction of scanlines for rows", "vertical_byte = whether to align bits in a byte vertically or not", "msb = when bits<8, store pixels msb first", "color_order = re-orders the colour values that are supplied via setColor" ]] ], "return" : ["JsVar","The new Graphics object"], "return_object" : "Graphics" } Create a Graphics object that renders to an Array Buffer. This will have a field called 'buffer' that can get used to get at the buffer itself */ JsVar *jswrap_graphics_createArrayBuffer(int width, int height, int bpp, JsVar *options) { if (width<=0 || height<=0 || width>32767 || height>32767) { jsExceptionHere(JSET_ERROR, "Invalid Size"); return 0; } if (!isValidBPP(bpp)) { jsExceptionHere(JSET_ERROR, "Invalid BPP"); return 0; } JsVar *parent = jspNewObject(0, "Graphics"); if (!parent) return 0; // low memory JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_ARRAYBUFFER; gfx.data.flags = JSGRAPHICSFLAGS_NONE; gfx.graphicsVar = parent; gfx.data.width = (unsigned short)width; gfx.data.height = (unsigned short)height; gfx.data.bpp = (unsigned char)bpp; if (jsvIsObject(options)) { if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "zigzag", 0))) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG); if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "msb", 0))) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_MSB); if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "vertical_byte", 0))) { if (gfx.data.bpp==1) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE); else { jsExceptionHere(JSET_ERROR, "vertical_byte only works for 1bpp ArrayBuffers\n"); return 0; } if (gfx.data.height&7) { jsExceptionHere(JSET_ERROR, "height must be a multiple of 8 when using vertical_byte\n"); return 0; } } JsVar *colorv = jsvObjectGetChild(options, "color_order", 0); if (colorv) { if (jsvIsStringEqual(colorv, "rgb")) ; // The default else if (!jsvIsStringEqual(colorv, "brg")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BRG); else if (!jsvIsStringEqual(colorv, "bgr")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BGR); else if (!jsvIsStringEqual(colorv, "gbr")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GBR); else if (!jsvIsStringEqual(colorv, "grb")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GRB); else if (!jsvIsStringEqual(colorv, "rbg")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_RBG); else jsWarn("color_order must be 3 characters"); jsvUnLock(colorv); } } lcdInit_ArrayBuffer(&gfx); graphicsSetVar(&gfx); return parent; } /*JSON{ "type" : "staticmethod", "class" : "Graphics", "name" : "createCallback", "ifndef" : "SAVE_ON_FLASH", "generate" : "jswrap_graphics_createCallback", "params" : [ ["width","int32","Pixels wide"], ["height","int32","Pixels high"], ["bpp","int32","Number of bits per pixel"], ["callback","JsVar","A function of the form ```function(x,y,col)``` that is called whenever a pixel needs to be drawn, or an object with: ```{setPixel:function(x,y,col),fillRect:function(x1,y1,x2,y2,col)}```. All arguments are already bounds checked."] ], "return" : ["JsVar","The new Graphics object"], "return_object" : "Graphics" } Create a Graphics object that renders by calling a JavaScript callback function to draw pixels */ JsVar *jswrap_graphics_createCallback(int width, int height, int bpp, JsVar *callback) { if (width<=0 || height<=0 || width>32767 || height>32767) { jsExceptionHere(JSET_ERROR, "Invalid Size"); return 0; } if (!isValidBPP(bpp)) { jsExceptionHere(JSET_ERROR, "Invalid BPP"); return 0; } JsVar *callbackSetPixel = 0; JsVar *callbackFillRect = 0; if (jsvIsObject(callback)) { jsvUnLock(callbackSetPixel); callbackSetPixel = jsvObjectGetChild(callback, "setPixel", 0); callbackFillRect = jsvObjectGetChild(callback, "fillRect", 0); } else callbackSetPixel = jsvLockAgain(callback); if (!jsvIsFunction(callbackSetPixel)) { jsExceptionHere(JSET_ERROR, "Expecting Callback Function or an Object but got %t", callbackSetPixel); jsvUnLock2(callbackSetPixel, callbackFillRect); return 0; } if (!jsvIsUndefined(callbackFillRect) && !jsvIsFunction(callbackFillRect)) { jsExceptionHere(JSET_ERROR, "Expecting Callback Function or an Object but got %t", callbackFillRect); jsvUnLock2(callbackSetPixel, callbackFillRect); return 0; } JsVar *parent = jspNewObject(0, "Graphics"); if (!parent) return 0; // low memory JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_JS; gfx.graphicsVar = parent; gfx.data.width = (unsigned short)width; gfx.data.height = (unsigned short)height; gfx.data.bpp = (unsigned char)bpp; lcdInit_JS(&gfx, callbackSetPixel, callbackFillRect); graphicsSetVar(&gfx); jsvUnLock2(callbackSetPixel, callbackFillRect); return parent; } #ifdef USE_LCD_SDL /*JSON{ "type" : "staticmethod", "class" : "Graphics", "name" : "createSDL", "ifdef" : "USE_LCD_SDL", "generate" : "jswrap_graphics_createSDL", "params" : [ ["width","int32","Pixels wide"], ["height","int32","Pixels high"] ], "return" : ["JsVar","The new Graphics object"], "return_object" : "Graphics" } Create a Graphics object that renders to SDL window (Linux-based devices only) */ JsVar *jswrap_graphics_createSDL(int width, int height) { if (width<=0 || height<=0 || width>32767 || height>32767) { jsExceptionHere(JSET_ERROR, "Invalid Size"); return 0; } JsVar *parent = jspNewObject(0, "Graphics"); if (!parent) return 0; // low memory JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_SDL; gfx.graphicsVar = parent; gfx.data.width = (unsigned short)width; gfx.data.height = (unsigned short)height; gfx.data.bpp = 32; lcdInit_SDL(&gfx); graphicsSetVar(&gfx); return parent; } #endif /*JSON{ "type" : "method", "class" : "Graphics", "name" : "getWidth", "generate_full" : "jswrap_graphics_getWidthOrHeight(parent, false)", "return" : ["int","The width of the LCD"] } The width of the LCD */ /*JSON{ "type" : "method", "class" : "Graphics", "name" : "getHeight", "generate_full" : "jswrap_graphics_getWidthOrHeight(parent, true)", "return" : ["int","The height of the LCD"] } The height of the LCD */ int jswrap_graphics_getWidthOrHeight(JsVar *parent, bool height) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0; if (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY) height=!height; return height ? gfx.data.height : gfx.data.width; } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "clear", "generate" : "jswrap_graphics_clear" } Clear the LCD with the Background Color */ void jswrap_graphics_clear(JsVar *parent) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsClear(&gfx); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "fillRect", "generate" : "jswrap_graphics_fillRect", "params" : [ ["x1","int32","The left"], ["y1","int32","The top"], ["x2","int32","The right"], ["y2","int32","The bottom"] ] } Fill a rectangular area in the Foreground Color */ void jswrap_graphics_fillRect(JsVar *parent, int x1, int y1, int x2, int y2) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsFillRect(&gfx, (short)x1,(short)y1,(short)x2,(short)y2); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "drawRect", "generate" : "jswrap_graphics_drawRect", "params" : [ ["x1","int32","The left"], ["y1","int32","The top"], ["x2","int32","The right"], ["y2","int32","The bottom"] ] } Draw an unfilled rectangle 1px wide in the Foreground Color */ void jswrap_graphics_drawRect(JsVar *parent, int x1, int y1, int x2, int y2) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsDrawRect(&gfx, (short)x1,(short)y1,(short)x2,(short)y2); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "fillCircle", "generate" : "jswrap_graphics_fillCircle", "params" : [ ["x","int32","The X axis"], ["y","int32","The Y axis"], ["rad","int32","The circle radius"] ] } Draw a filled circle in the Foreground Color */ void jswrap_graphics_fillCircle(JsVar *parent, int x, int y, int rad) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsFillCircle(&gfx, (short)x,(short)y,(short)rad); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "drawCircle", "generate" : "jswrap_graphics_drawCircle", "params" : [ ["x","int32","The X axis"], ["y","int32","The Y axis"], ["rad","int32","The circle radius"] ] } Draw an unfilled circle 1px wide in the Foreground Color */ void jswrap_graphics_drawCircle(JsVar *parent, int x, int y, int rad) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsDrawCircle(&gfx, (short)x,(short)y,(short)rad); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "getPixel", "generate" : "jswrap_graphics_getPixel", "params" : [ ["x","int32","The left"], ["y","int32","The top"] ], "return" : ["int32","The color"] } Get a pixel's color */ int jswrap_graphics_getPixel(JsVar *parent, int x, int y) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0; return (int)graphicsGetPixel(&gfx, (short)x, (short)y); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setPixel", "generate" : "jswrap_graphics_setPixel", "params" : [ ["x","int32","The left"], ["y","int32","The top"], ["col","JsVar","The color"] ] } Set a pixel's color */ void jswrap_graphics_setPixel(JsVar *parent, int x, int y, JsVar *color) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; unsigned int col = gfx.data.fgColor; if (!jsvIsUndefined(color)) col = (unsigned int)jsvGetInteger(color); graphicsSetPixel(&gfx, (short)x, (short)y, col); gfx.data.cursorX = (short)x; gfx.data.cursorY = (short)y; graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setColor", "generate_full" : "jswrap_graphics_setColorX(parent, r,g,b, true)", "params" : [ ["r","JsVar","Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order"], ["g","JsVar","Green (between 0 and 1)"], ["b","JsVar","Blue (between 0 and 1)"] ] } Set the color to use for subsequent drawing operations */ /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setBgColor", "generate_full" : "jswrap_graphics_setColorX(parent, r,g,b, false)", "params" : [ ["r","JsVar","Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order"], ["g","JsVar","Green (between 0 and 1)"], ["b","JsVar","Blue (between 0 and 1)"] ] } Set the background color to use for subsequent drawing operations */ void jswrap_graphics_setColorX(JsVar *parent, JsVar *r, JsVar *g, JsVar *b, bool isForeground) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; unsigned int color = 0; JsVarFloat rf, gf, bf; rf = jsvGetFloat(r); gf = jsvGetFloat(g); bf = jsvGetFloat(b); if (!jsvIsUndefined(g) && !jsvIsUndefined(b)) { int ri = (int)(rf*256); int gi = (int)(gf*256); int bi = (int)(bf*256); if (ri>255) ri=255; if (gi>255) gi=255; if (bi>255) bi=255; if (ri<0) ri=0; if (gi<0) gi=0; if (bi<0) bi=0; // Check if we need to twiddle colors int colorMask = gfx.data.flags & JSGRAPHICSFLAGS_COLOR_MASK; if (colorMask) { int tmpr, tmpg, tmpb; tmpr = ri; tmpg = gi; tmpb = bi; switch (colorMask) { case JSGRAPHICSFLAGS_COLOR_BRG: ri = tmpb; gi = tmpr; bi = tmpg; break; case JSGRAPHICSFLAGS_COLOR_BGR: ri = tmpb; bi = tmpr; break; case JSGRAPHICSFLAGS_COLOR_GBR: ri = tmpg; gi = tmpb; bi = tmpr; break; case JSGRAPHICSFLAGS_COLOR_GRB: ri = tmpg; gi = tmpr; break; case JSGRAPHICSFLAGS_COLOR_RBG: gi = tmpb; bi = tmpg; break; default: break; } } if (gfx.data.bpp==16) { color = (unsigned int)((bi>>3) | (gi>>2)<<5 | (ri>>3)<<11); } else if (gfx.data.bpp==32) { color = 0xFF000000 | (unsigned int)(bi | (gi<<8) | (ri<<16)); } else if (gfx.data.bpp==24) { color = (unsigned int)(bi | (gi<<8) | (ri<<16)); } else color = (unsigned int)(((ri+gi+bi)>=384) ? 0xFFFFFFFF : 0); } else { // just rgb color = (unsigned int)jsvGetInteger(r); } if (isForeground) gfx.data.fgColor = color; else gfx.data.bgColor = color; graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "getColor", "generate_full" : "jswrap_graphics_getColorX(parent, true)", "return" : ["int","The integer value of the colour"] } Get the color to use for subsequent drawing operations */ /*JSON{ "type" : "method", "class" : "Graphics", "name" : "getBgColor", "generate_full" : "jswrap_graphics_getColorX(parent, false)", "return" : ["int","The integer value of the colour"] } Get the background color to use for subsequent drawing operations */ JsVarInt jswrap_graphics_getColorX(JsVar *parent, bool isForeground) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0; return (JsVarInt)((isForeground ? gfx.data.fgColor : gfx.data.bgColor) & ((1UL<<gfx.data.bpp)-1)); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setFontBitmap", "generate_full" : "jswrap_graphics_setFontSizeX(parent, JSGRAPHICS_FONTSIZE_4X6, false)" } Make subsequent calls to `drawString` use the built-in 4x6 pixel bitmapped Font */ /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setFontVector", "ifndef" : "SAVE_ON_FLASH", "generate_full" : "jswrap_graphics_setFontSizeX(parent, size, true)", "params" : [ ["size","int32","The height of the font, as an integer"] ] } Make subsequent calls to `drawString` use a Vector Font of the given height */ void jswrap_graphics_setFontSizeX(JsVar *parent, int size, bool checkValid) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; if (checkValid) { if (size<1) size=1; if (size>1023) size=1023; } if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) { jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_BMP); jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH); jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_HEIGHT); jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR); } gfx.data.fontSize = (short)size; graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setFontCustom", "generate" : "jswrap_graphics_setFontCustom", "params" : [ ["bitmap","JsVar","A column-first, MSB-first, 1bpp bitmap containing the font bitmap"], ["firstChar","int32","The first character in the font - usually 32 (space)"], ["width","JsVar","The width of each character in the font. Either an integer, or a string where each character represents the width"], ["height","int32","The height as an integer"] ] } Make subsequent calls to `drawString` use a Custom Font of the given height. See the [Fonts page](http://www.espruino.com/Fonts) for more information about custom fonts and how to create them. */ void jswrap_graphics_setFontCustom(JsVar *parent, JsVar *bitmap, int firstChar, JsVar *width, int height) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; if (!jsvIsString(bitmap)) { jsExceptionHere(JSET_ERROR, "Font bitmap must be a String"); return; } if (firstChar<0 || firstChar>255) { jsExceptionHere(JSET_ERROR, "First character out of range"); return; } if (!jsvIsString(width) && !jsvIsInt(width)) { jsExceptionHere(JSET_ERROR, "Font width must be a String or an integer"); return; } if (height<=0 || height>255) { jsExceptionHere(JSET_ERROR, "Invalid height"); return; } jsvObjectSetChild(parent, JSGRAPHICS_CUSTOMFONT_BMP, bitmap); jsvObjectSetChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH, width); jsvObjectSetChildAndUnLock(parent, JSGRAPHICS_CUSTOMFONT_HEIGHT, jsvNewFromInteger(height)); jsvObjectSetChildAndUnLock(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR, jsvNewFromInteger(firstChar)); gfx.data.fontSize = JSGRAPHICS_FONTSIZE_CUSTOM; graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setFontAlign", "generate" : "jswrap_graphics_setFontAlign", "params" : [ ["x","int32","X alignment. -1=left (default), 0=center, 1=right"], ["y","int32","Y alignment. -1=top (default), 0=center, 1=bottom"], ["rotation","int32","Rotation of the text. 0=normal, 1=90 degrees clockwise, 2=180, 3=270"] ] } Set the alignment for subsequent calls to `drawString` */ void jswrap_graphics_setFontAlign(JsVar *parent, int x, int y, int r) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; if (x<-1) x=-1; if (x>1) x=1; if (y<-1) y=-1; if (y>1) y=1; if (r<0) r=0; if (r>3) r=3; gfx.data.fontAlignX = x; gfx.data.fontAlignY = y; gfx.data.fontRotate = r; graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "drawString", "generate" : "jswrap_graphics_drawString", "params" : [ ["str","JsVar","The string"], ["x","int32","The X position of the leftmost pixel"], ["y","int32","The Y position of the topmost pixel"] ] } Draw a string of text in the current font */ void jswrap_graphics_drawString(JsVar *parent, JsVar *var, int x, int y) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; JsVar *customBitmap = 0, *customWidth = 0; int customHeight = 0, customFirstChar = 0; if (gfx.data.fontSize>0) { customHeight = gfx.data.fontSize; } else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_4X6) { customHeight = 6; } else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) { customBitmap = jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_BMP, 0); customWidth = jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH, 0); customHeight = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_HEIGHT, 0)); customFirstChar = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR, 0)); } // Handle text rotation JsGraphicsFlags oldFlags = gfx.data.flags; if (gfx.data.fontRotate==1) { gfx.data.flags ^= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_X; int t = gfx.data.width - (x+1); x = y; y = t; } else if (gfx.data.fontRotate==2) { gfx.data.flags ^= JSGRAPHICSFLAGS_INVERT_X | JSGRAPHICSFLAGS_INVERT_Y; x = gfx.data.width - (x+1); y = gfx.data.height - (y+1); } else if (gfx.data.fontRotate==3) { gfx.data.flags ^= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_Y; int t = gfx.data.height - (y+1); y = x; x = t; } // Handle font alignment if (gfx.data.fontAlignX>=0) x -= jswrap_graphics_stringWidth(parent, var) * (gfx.data.fontAlignX+1)/2; if (gfx.data.fontAlignY>=0) y -= customHeight * (gfx.data.fontAlignX+1)/2; int maxX = (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY) ? gfx.data.height : gfx.data.width; int maxY = (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY) ? gfx.data.width : gfx.data.height; int startx = x; JsVar *str = jsvAsString(var, false); JsvStringIterator it; jsvStringIteratorNew(&it, str, 0); while (jsvStringIteratorHasChar(&it)) { char ch = jsvStringIteratorGetChar(&it); if (ch=='\n') { x = startx; y += customHeight; jsvStringIteratorNext(&it); continue; } if (gfx.data.fontSize>0) { #ifndef SAVE_ON_FLASH int w = (int)graphicsVectorCharWidth(&gfx, gfx.data.fontSize, ch); if (x>-w && x<maxX && y>-gfx.data.fontSize && y<maxY) graphicsFillVectorChar(&gfx, (short)x, (short)y, gfx.data.fontSize, ch); x+=w; #endif } else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_4X6) { if (x>-4 && x<maxX && y>-6 && y<maxY) graphicsDrawChar4x6(&gfx, (short)x, (short)y, ch); x+=4; } else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) { // get char width and offset in string int width = 0, bmpOffset = 0; if (jsvIsString(customWidth)) { if (ch>=customFirstChar) { JsvStringIterator wit; jsvStringIteratorNew(&wit, customWidth, 0); while (jsvStringIteratorHasChar(&wit) && (int)jsvStringIteratorGetIndex(&wit)<(ch-customFirstChar)) { bmpOffset += (unsigned char)jsvStringIteratorGetChar(&wit); jsvStringIteratorNext(&wit); } width = (unsigned char)jsvStringIteratorGetChar(&wit); jsvStringIteratorFree(&wit); } } else { width = (int)jsvGetInteger(customWidth); bmpOffset = width*(ch-customFirstChar); } if (ch>=customFirstChar && (x>-width) && (x<maxX) && (y>-customHeight) && y<maxY) { bmpOffset *= customHeight; // now render character JsvStringIterator cit; jsvStringIteratorNew(&cit, customBitmap, (size_t)bmpOffset>>3); bmpOffset &= 7; int cx,cy; for (cx=0;cx<width;cx++) { for (cy=0;cy<customHeight;cy++) { if ((jsvStringIteratorGetChar(&cit)<<bmpOffset)&128) graphicsSetPixel(&gfx, (short)(cx+x), (short)(cy+y), gfx.data.fgColor); bmpOffset++; if (bmpOffset==8) { bmpOffset=0; jsvStringIteratorNext(&cit); } } } jsvStringIteratorFree(&cit); } x += width; } if (jspIsInterrupted()) break; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); jsvUnLock3(str, customBitmap, customWidth); gfx.data.flags = oldFlags; // restore flags because of text rotation graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "stringWidth", "generate" : "jswrap_graphics_stringWidth", "params" : [ ["str","JsVar","The string"] ], "return" : ["int","The length of the string in pixels"] } Return the size in pixels of a string of text in the current font */ JsVarInt jswrap_graphics_stringWidth(JsVar *parent, JsVar *var) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0; JsVar *customWidth = 0; int customFirstChar = 0; if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) { customWidth = jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH, 0); customFirstChar = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR, 0)); } JsVar *str = jsvAsString(var, false); JsvStringIterator it; jsvStringIteratorNew(&it, str, 0); int width = 0; while (jsvStringIteratorHasChar(&it)) { char ch = jsvStringIteratorGetChar(&it); if (gfx.data.fontSize>0) { #ifndef SAVE_ON_FLASH width += (int)graphicsVectorCharWidth(&gfx, gfx.data.fontSize, ch); #endif } else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_4X6) { width += 4; } else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) { if (jsvIsString(customWidth)) { if (ch>=customFirstChar) width += (unsigned char)jsvGetCharInString(customWidth, (size_t)(ch-customFirstChar)); } else width += (int)jsvGetInteger(customWidth); } jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); jsvUnLock2(str, customWidth); return width; } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "drawLine", "generate" : "jswrap_graphics_drawLine", "params" : [ ["x1","int32","The left"], ["y1","int32","The top"], ["x2","int32","The right"], ["y2","int32","The bottom"] ] } Draw a line between x1,y1 and x2,y2 in the current foreground color */ void jswrap_graphics_drawLine(JsVar *parent, int x1, int y1, int x2, int y2) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsDrawLine(&gfx, (short)x1,(short)y1,(short)x2,(short)y2); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "lineTo", "generate" : "jswrap_graphics_lineTo", "params" : [ ["x","int32","X value"], ["y","int32","Y value"] ] } Draw a line from the last position of lineTo or moveTo to this position */ void jswrap_graphics_lineTo(JsVar *parent, int x, int y) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsDrawLine(&gfx, gfx.data.cursorX, gfx.data.cursorY, (short)x, (short)y); gfx.data.cursorX = (short)x; gfx.data.cursorY = (short)y; graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "moveTo", "generate" : "jswrap_graphics_moveTo", "params" : [ ["x","int32","X value"], ["y","int32","Y value"] ] } Move the cursor to a position - see lineTo */ void jswrap_graphics_moveTo(JsVar *parent, int x, int y) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; gfx.data.cursorX = (short)x; gfx.data.cursorY = (short)y; graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "fillPoly", "generate" : "jswrap_graphics_fillPoly", "params" : [ ["poly","JsVar","An array of vertices, of the form ```[x1,y1,x2,y2,x3,y3,etc]```"] ] } Draw a filled polygon in the current foreground color */ void jswrap_graphics_fillPoly(JsVar *parent, JsVar *poly) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; if (!jsvIsIterable(poly)) return; const int maxVerts = 128; short verts[maxVerts]; int idx = 0; JsvIterator it; jsvIteratorNew(&it, poly, JSIF_EVERY_ARRAY_ELEMENT); while (jsvIteratorHasElement(&it) && idx<maxVerts) { verts[idx++] = (short)jsvIteratorGetIntegerValue(&it); jsvIteratorNext(&it); } jsvIteratorFree(&it); if (idx==maxVerts) { jsWarn("Maximum number of points (%d) exceeded for fillPoly", maxVerts/2); } graphicsFillPoly(&gfx, idx/2, verts); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "setRotation", "generate" : "jswrap_graphics_setRotation", "params" : [ ["rotation","int32","The clockwise rotation. 0 for no rotation, 1 for 90 degrees, 2 for 180, 3 for 270"], ["reflect","bool","Whether to reflect the image"] ] } Set the current rotation of the graphics device. */ void jswrap_graphics_setRotation(JsVar *parent, int rotation, bool reflect) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; // clear flags gfx.data.flags &= (JsGraphicsFlags)~(JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_X | JSGRAPHICSFLAGS_INVERT_Y); // set flags switch (rotation) { case 0: break; case 1: gfx.data.flags |= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_X; break; case 2: gfx.data.flags |= JSGRAPHICSFLAGS_INVERT_X | JSGRAPHICSFLAGS_INVERT_Y; break; case 3: gfx.data.flags |= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_Y; break; } if (reflect) { if (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY) gfx.data.flags ^= JSGRAPHICSFLAGS_INVERT_Y; else gfx.data.flags ^= JSGRAPHICSFLAGS_INVERT_X; } graphicsSetVar(&gfx); } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "drawImage", "generate" : "jswrap_graphics_drawImage", "params" : [ ["image","JsVar","An object with the following fields `{ width : int, height : int, bpp : int, buffer : ArrayBuffer, transparent: optional int }`. bpp = bits per pixel, transparent (if defined) is the colour that will be treated as transparent"], ["x","int32","The X offset to draw the image"], ["y","int32","The Y offset to draw the image"] ] } Draw an image at the specified position. If the image is 1 bit, the graphics foreground/background colours will be used. Otherwise color data will be copied as-is. Bitmaps are rendered MSB-first */ void jswrap_graphics_drawImage(JsVar *parent, JsVar *image, int xPos, int yPos) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; if (!jsvIsObject(image)) { jsExceptionHere(JSET_ERROR, "Expecting first argument to be an object"); return; } int imageWidth = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(image, "width", 0)); int imageHeight = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(image, "height", 0)); int imageBpp = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(image, "bpp", 0)); unsigned int imageBitMask = (unsigned int)((1L<<imageBpp)-1L); JsVar *transpVar = jsvObjectGetChild(image, "transparent", 0); bool imageIsTransparent = transpVar!=0; unsigned int imageTransparentCol = (unsigned int)jsvGetInteger(transpVar); jsvUnLock(transpVar); JsVar *imageBuffer = jsvObjectGetChild(image, "buffer", 0); if (!(jsvIsArrayBuffer(imageBuffer) && imageWidth>0 && imageHeight>0 && imageBpp>0 && imageBpp<=32)) { jsExceptionHere(JSET_ERROR, "Expecting first argument to a valid Image"); jsvUnLock(imageBuffer); return; } JsVar *imageBufferString = jsvGetArrayBufferBackingString(imageBuffer); jsvUnLock(imageBuffer); int x=0, y=0; int bits=0; unsigned int colData = 0; JsvStringIterator it; jsvStringIteratorNew(&it, imageBufferString, 0); while ((bits>=imageBpp || jsvStringIteratorHasChar(&it)) && y<imageHeight) { // Get the data we need... while (bits < imageBpp) { colData = (colData<<8) | ((unsigned char)jsvStringIteratorGetChar(&it)); jsvStringIteratorNext(&it); bits += 8; } // extract just the bits we want unsigned int col = (colData>>(bits-imageBpp))&imageBitMask; bits -= imageBpp; // Try and write pixel! if (!imageIsTransparent || imageTransparentCol!=col) { if (imageBpp==1) col = col ? gfx.data.fgColor : gfx.data.bgColor; graphicsSetPixel(&gfx, (short)(x+xPos), (short)(y+yPos), col); } // Go to next pixel x++; if (x>=imageWidth) { x=0; y++; // we don't care about image height - we'll stop next time... } } jsvStringIteratorFree(&it); jsvUnLock(imageBufferString); graphicsSetVar(&gfx); // gfx data changed because modified area } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "getModified", "generate" : "jswrap_graphics_getModified", "params" : [ ["reset","bool","Whether to reset the modified area or not"] ], "return" : ["JsVar","An object {x1,y1,x2,y2} containing the modified area, or undefined if not modified"] } Return the area of the Graphics canvas that has been modified, and optionally clear the modified area to 0. For instance if `g.setPixel(10,20)` was called, this would return `{x1:10, y1:20, x2:10, y2:20}` */ JsVar *jswrap_graphics_getModified(JsVar *parent, bool reset) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0; JsVar *obj = 0; if (gfx.data.modMinX <= gfx.data.modMaxX) { // do we have a rect? obj = jsvNewObject(); if (obj) { jsvObjectSetChildAndUnLock(obj, "x1", jsvNewFromInteger(gfx.data.modMinX)); jsvObjectSetChildAndUnLock(obj, "y1", jsvNewFromInteger(gfx.data.modMinY)); jsvObjectSetChildAndUnLock(obj, "x2", jsvNewFromInteger(gfx.data.modMaxX)); jsvObjectSetChildAndUnLock(obj, "y2", jsvNewFromInteger(gfx.data.modMaxY)); } } if (reset) { gfx.data.modMaxX = -32768; gfx.data.modMaxY = -32768; gfx.data.modMinX = 32767; gfx.data.modMinY = 32767; graphicsSetVar(&gfx); } return obj; } /*JSON{ "type" : "method", "class" : "Graphics", "name" : "scroll", "generate" : "jswrap_graphics_scroll", "params" : [ ["x","int32","X direction. >0 = to right"], ["y","int32","Y direction. >0 = down"] ] } Scroll the contents of this graphics in a certain direction. The remaining area is filled with the background color. Note: This uses repeated pixel reads and writes, so will not work on platforms that don't support pixel reads. */ void jswrap_graphics_scroll(JsVar *parent, int xdir, int ydir) { JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return; graphicsScroll(&gfx, xdir, ydir); // update modified area graphicsSetVar(&gfx); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_157_1
crossvul-cpp_data_good_4652_0
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Francesco Fondelli (francesco dot fondelli, gmail dot com) */ /* \summary: Autosar SOME/IP Protocol printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "netdissect-stdinc.h" #include "netdissect.h" #include "extract.h" #include "udp.h" /* * SOMEIP Header (R19-11) * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Message ID (Service ID/Method ID) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Request ID (Client ID/Session ID) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Protocol Ver | Interface Ver | Message Type | Return Code | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Payload | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ static const struct tok message_type_values[] = { { 0x00, "REQUEST" }, { 0x01, "REQUEST_NO_RETURN" }, { 0x02, "NOTIFICATION" }, { 0x80, "RESPONSE" }, { 0x81, "ERROR" }, { 0x20, "TP_REQUEST" }, { 0x21, "TP_REQUEST_NO_RETURN" }, { 0x22, "TP_NOTIFICATION" }, { 0xa0, "TP_RESPONSE" }, { 0xa1, "TP_ERROR" }, { 0, NULL } }; static const struct tok return_code_values[] = { { 0x00, "E_OK" }, { 0x01, "E_NOT_OK" }, { 0x02, "E_UNKNOWN_SERVICE" }, { 0x03, "E_UNKNOWN_METHOD" }, { 0x04, "E_NOT_READY" }, { 0x05, "E_NOT_REACHABLE" }, { 0x06, "E_TIMEOUT" }, { 0x07, "E_WRONG_PROTOCOL_VERSION" }, { 0x08, "E_WRONG_INTERFACE_VERSION" }, { 0x09, "E_MALFORMED_MESSAGE" }, { 0x0a, "E_WRONG_MESSAGE_TYPE" }, { 0x0b, "E_E2E_REPEATED" }, { 0x0c, "E_E2E_WRONG_SEQUENCE" }, { 0x0d, "E_E2E" }, { 0x0e, "E_E2E_NOT_AVAILABLE" }, { 0x0f, "E_E2E_NO_NEW_DATA" }, { 0, NULL } }; void someip_print(netdissect_options *ndo, const u_char *bp, u_int len) { uint32_t message_id; uint16_t service_id; uint16_t method_or_event_id; uint8_t event_flag; uint32_t message_len; uint32_t request_id; uint16_t client_id; uint16_t session_id; uint8_t protocol_version; uint8_t interface_version; uint8_t message_type; uint8_t return_code; ndo->ndo_protocol = "someip"; if (len < 16) { nd_print_trunc(ndo); return; } message_id = GET_BE_U_4(bp); service_id = message_id >> 16; event_flag = (message_id & 0x00008000) >> 15; method_or_event_id = message_id & 0x00007FFF; bp += 4; message_len = GET_BE_U_4(bp); bp += 4; request_id = GET_BE_U_4(bp); client_id = request_id >> 16; session_id = request_id & 0x0000FFFF; bp += 4; protocol_version = GET_U_1(bp); bp += 1; interface_version = GET_U_1(bp); bp += 1; message_type = GET_U_1(bp); bp += 1; return_code = GET_U_1(bp); bp += 1; ND_PRINT("SOMEIP, service %u, %s %u, len %u, client %u, session %u, " "pver %u, iver %u, msgtype %s, retcode %s\n", service_id, event_flag ? "event" : "method", method_or_event_id, message_len, client_id, session_id, protocol_version, interface_version, tok2str(message_type_values, "Unknown", message_type), tok2str(return_code_values, "Unknown", return_code)); return; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_4652_0
crossvul-cpp_data_bad_5314_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT U U M M % % Q Q U U A A NN N T U U MM MM % % Q Q U U AAAAA N N N T U U M M M % % Q QQ U U A A N NN T U U M M % % QQQQ UUU A A N N T UUU M M % % % % IIIII M M PPPP OOO RRRR TTTTT % % I MM MM P P O O R R T % % I M M M PPPP O O RRRR T % % I M M P O O R R T % % IIIII M M P OOO R R T % % % % MagickCore Methods to Import Quantum Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % 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/property.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/color-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/utility.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p o r t Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImportQuantumPixels() transfers one or more pixel components from a user % supplied buffer into the image pixel cache of an image. The pixels are % expected in network byte order. It returns MagickTrue if the pixels are % successfully transferred, otherwise MagickFalse. % % The format of the ImportQuantumPixels method is: % % size_t ImportQuantumPixels(const Image *image,CacheView *image_view, % QuantumInfo *quantum_info,const QuantumType quantum_type, % const unsigned char *magick_restrict pixels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o image_view: the image cache view. % % o quantum_info: the quantum info. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % % o pixels: The pixel components are transferred from this buffer. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PushColormapIndex(const Image *image,const size_t index, MagickBooleanType *range_exception) { if (index < image->colors) return((Quantum) index); *range_exception=MagickTrue; return((Quantum) 0); } static inline const unsigned char *PushDoublePixel(QuantumInfo *quantum_info, const unsigned char *magick_restrict pixels,double *pixel) { double *p; unsigned char quantum[8]; if (quantum_info->endian == LSBEndian) { quantum[0]=(*pixels++); quantum[1]=(*pixels++); quantum[2]=(*pixels++); quantum[3]=(*pixels++); quantum[4]=(*pixels++); quantum[5]=(*pixels++); quantum[6]=(*pixels++); quantum[7]=(*pixels++); p=(double *) quantum; *pixel=(*p); *pixel-=quantum_info->minimum; *pixel*=quantum_info->scale; return(pixels); } quantum[7]=(*pixels++); quantum[6]=(*pixels++); quantum[5]=(*pixels++); quantum[4]=(*pixels++); quantum[3]=(*pixels++); quantum[2]=(*pixels++); quantum[1]=(*pixels++); quantum[0]=(*pixels++); p=(double *) quantum; *pixel=(*p); *pixel-=quantum_info->minimum; *pixel*=quantum_info->scale; return(pixels); } static inline const unsigned char *PushFloatPixel(QuantumInfo *quantum_info, const unsigned char *magick_restrict pixels,float *pixel) { float *p; unsigned char quantum[4]; if (quantum_info->endian == LSBEndian) { quantum[0]=(*pixels++); quantum[1]=(*pixels++); quantum[2]=(*pixels++); quantum[3]=(*pixels++); p=(float *) quantum; *pixel=(*p); *pixel-=quantum_info->minimum; *pixel*=quantum_info->scale; return(pixels); } quantum[3]=(*pixels++); quantum[2]=(*pixels++); quantum[1]=(*pixels++); quantum[0]=(*pixels++); p=(float *) quantum; *pixel=(*p); *pixel-=quantum_info->minimum; *pixel*=quantum_info->scale; return(pixels); } static inline const unsigned char *PushQuantumPixel(QuantumInfo *quantum_info, const unsigned char *magick_restrict pixels,unsigned int *quantum) { register ssize_t i; register size_t quantum_bits; *quantum=(QuantumAny) 0; for (i=(ssize_t) quantum_info->depth; i > 0L; ) { if (quantum_info->state.bits == 0UL) { quantum_info->state.pixel=(*pixels++); quantum_info->state.bits=8UL; } quantum_bits=(size_t) i; if (quantum_bits > quantum_info->state.bits) quantum_bits=quantum_info->state.bits; i-=(ssize_t) quantum_bits; quantum_info->state.bits-=quantum_bits; *quantum=(unsigned int) ((*quantum << quantum_bits) | ((quantum_info->state.pixel >> quantum_info->state.bits) &~ ((~0UL) << quantum_bits))); } return(pixels); } static inline const unsigned char *PushQuantumLongPixel( QuantumInfo *quantum_info,const unsigned char *magick_restrict pixels, unsigned int *quantum) { register ssize_t i; register size_t quantum_bits; *quantum=0UL; for (i=(ssize_t) quantum_info->depth; i > 0; ) { if (quantum_info->state.bits == 0) { pixels=PushLongPixel(quantum_info->endian,pixels, &quantum_info->state.pixel); quantum_info->state.bits=32U; } quantum_bits=(size_t) i; if (quantum_bits > quantum_info->state.bits) quantum_bits=quantum_info->state.bits; *quantum|=(((quantum_info->state.pixel >> (32U-quantum_info->state.bits)) & quantum_info->state.mask[quantum_bits]) << (quantum_info->depth-i)); i-=(ssize_t) quantum_bits; quantum_info->state.bits-=quantum_bits; } return(pixels); } static void ImportAlphaQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportBGRQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range),q); SetPixelGreen(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range), q); SetPixelBlue(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } if (quantum_info->quantum == 32U) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { unsigned short pixel; for (x=0; x < (ssize_t) (3*number_pixels-1); x+=2) { p=PushShortPixel(quantum_info->endian,p,&pixel); switch (x % 3) { default: case 0: { SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 1: { SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 2: { SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); break; } } p=PushShortPixel(quantum_info->endian,p,&pixel); switch ((x+1) % 3) { default: case 0: { SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 1: { SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 2: { SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); break; } } p+=quantum_info->pad; } for (bit=0; bit < (ssize_t) (3*number_pixels % 2); bit++) { p=PushShortPixel(quantum_info->endian,p,&pixel); switch ((x+bit) % 3) { default: case 0: { SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 1: { SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 2: { SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); break; } } p+=quantum_info->pad; } if (bit != 0) p++; break; } if (quantum_info->quantum == 32U) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportBGRAQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x++) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } switch (i) { case 0: SetPixelRed(image,(Quantum) quantum,q); break; case 1: SetPixelGreen(image,(Quantum) quantum,q); break; case 2: SetPixelBlue(image,(Quantum) quantum,q); break; case 3: SetPixelAlpha(image,(Quantum) quantum,q); break; } n++; } p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportBGROQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelOpacity(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x++) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } switch (i) { case 0: SetPixelRed(image,(Quantum) quantum,q); break; case 1: SetPixelGreen(image,(Quantum) quantum,q); break; case 2: SetPixelBlue(image,(Quantum) quantum,q); break; case 3: SetPixelOpacity(image,(Quantum) quantum,q); break; } n++; } p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportBlackQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",image->filename); return; } switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportBlueQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportCbYCrYQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 10: { Quantum cbcr[4]; pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x+=2) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } cbcr[i]=(Quantum) (quantum); n++; } p+=quantum_info->pad; SetPixelRed(image,cbcr[1],q); SetPixelGreen(image,cbcr[0],q); SetPixelBlue(image,cbcr[2],q); q+=GetPixelChannels(image); SetPixelRed(image,cbcr[3],q); SetPixelGreen(image,cbcr[0],q); SetPixelBlue(image,cbcr[2],q); q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportCMYKQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",image->filename); return; } switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportCMYKAQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",image->filename); return; } switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportCMYKOQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",image->filename); return; } switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelOpacity(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlack(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlack(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportGrayQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 1: { register Quantum black, white; black=0; white=QuantumRange; if (quantum_info->min_is_white != MagickFalse) { black=QuantumRange; white=0; } for (x=0; x < ((ssize_t) number_pixels-7); x+=8) { for (bit=0; bit < 8; bit++) { SetPixelGray(image,((*p) & (1 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } p++; } for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++) { SetPixelGray(image,((*p) & (0x01 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } if (bit != 0) p++; break; } case 4: { register unsigned char pixel; range=GetQuantumRange(quantum_info->depth); for (x=0; x < ((ssize_t) number_pixels-1); x+=2) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); pixel=(unsigned char) ((*p) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p++; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { pixel=(unsigned char) (*p++ >> 4); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { if (image->endian == LSBEndian) { for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range), q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { unsigned short pixel; for (x=0; x < (ssize_t) (number_pixels-1); x+=2) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } if (bit != 0) p++; break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportGrayAlphaQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 1: { register unsigned char pixel; bit=0; for (x=((ssize_t) number_pixels-3); x > 0; x-=4) { for (bit=0; bit < 8; bit+=2) { pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01); SetPixelGray(image,(Quantum) (pixel == 0 ? 0 : QuantumRange),q); SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ? TransparentAlpha : OpaqueAlpha,q); q+=GetPixelChannels(image); } p++; } if ((number_pixels % 4) != 0) for (bit=3; bit >= (ssize_t) (4-(number_pixels % 4)); bit-=2) { pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01); SetPixelGray(image,(Quantum) (pixel != 0 ? 0 : QuantumRange),q); SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ? TransparentAlpha : OpaqueAlpha,q); q+=GetPixelChannels(image); } if (bit != 0) p++; break; } case 4: { register unsigned char pixel; range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); pixel=(unsigned char) ((*p) & 0xf); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p++; q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportGreenQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportIndexQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { MagickBooleanType range_exception; register ssize_t x; ssize_t bit; unsigned int pixel; if (image->storage_class != PseudoClass) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColormappedImageRequired","`%s'",image->filename); return; } range_exception=MagickFalse; switch (quantum_info->depth) { case 1: { register unsigned char pixel; for (x=0; x < ((ssize_t) number_pixels-7); x+=8) { for (bit=0; bit < 8; bit++) { if (quantum_info->min_is_white == MagickFalse) pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01); else pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception), q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); } p++; } for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++) { if (quantum_info->min_is_white == MagickFalse) pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01); else pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); } break; } case 4: { register unsigned char pixel; for (x=0; x < ((ssize_t) number_pixels-1); x+=2) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); pixel=(unsigned char) ((*p) & 0xf); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p++; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { pixel=(unsigned char) ((*p++ >> 4) & 0xf); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum( (double) QuantumRange*HalfToSinglePrecision(pixel)), &range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(pixel), &range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(pixel), &range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } if (range_exception != MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "InvalidColormapIndex","`%s'",image->filename); } static void ImportIndexAlphaQuantum(const Image *image, QuantumInfo *quantum_info,const MagickSizeType number_pixels, const unsigned char *magick_restrict p,Quantum *magick_restrict q, ExceptionInfo *exception) { MagickBooleanType range_exception; QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; if (image->storage_class != PseudoClass) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColormappedImageRequired","`%s'",image->filename); return; } range_exception=MagickFalse; switch (quantum_info->depth) { case 1: { register unsigned char pixel; for (x=((ssize_t) number_pixels-3); x > 0; x-=4) { for (bit=0; bit < 8; bit+=2) { if (quantum_info->min_is_white == MagickFalse) pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01); else pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01); SetPixelGray(image,(Quantum) (pixel == 0 ? 0 : QuantumRange),q); SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ? TransparentAlpha : OpaqueAlpha,q); SetPixelIndex(image,(Quantum) (pixel == 0 ? 0 : 1),q); q+=GetPixelChannels(image); } } if ((number_pixels % 4) != 0) for (bit=3; bit >= (ssize_t) (4-(number_pixels % 4)); bit-=2) { if (quantum_info->min_is_white == MagickFalse) pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01); else pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01); SetPixelIndex(image,(Quantum) (pixel == 0 ? 0 : 1),q); SetPixelGray(image,(Quantum) (pixel == 0 ? 0 : QuantumRange),q); SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ? TransparentAlpha : OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 4: { register unsigned char pixel; range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); pixel=(unsigned char) ((*p) & 0xf); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p++; q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum( (double) QuantumRange*HalfToSinglePrecision(pixel)), &range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelIndex(image,PushColormapIndex(image, ClampToQuantum(pixel),&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(pixel), &range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } if (range_exception != MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "InvalidColormapIndex","`%s'",image->filename); } static void ImportOpacityQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelOpacity(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportRedQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } static void ImportRGBQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range),q); SetPixelGreen(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range), q); SetPixelBlue(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } if (quantum_info->quantum == 32U) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { unsigned short pixel; for (x=0; x < (ssize_t) (3*number_pixels-1); x+=2) { p=PushShortPixel(quantum_info->endian,p,&pixel); switch (x % 3) { default: case 0: { SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 1: { SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 2: { SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); break; } } p=PushShortPixel(quantum_info->endian,p,&pixel); switch ((x+1) % 3) { default: case 0: { SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 1: { SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 2: { SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); break; } } p+=quantum_info->pad; } for (bit=0; bit < (ssize_t) (3*number_pixels % 2); bit++) { p=PushShortPixel(quantum_info->endian,p,&pixel); switch ((x+bit) % 3) { default: case 0: { SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 1: { SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); break; } case 2: { SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); break; } } p+=quantum_info->pad; } if (bit != 0) p++; break; } if (quantum_info->quantum == 32U) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumLongPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportRGBAQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x++) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } switch (i) { case 0: SetPixelRed(image,(Quantum) quantum,q); break; case 1: SetPixelGreen(image,(Quantum) quantum,q); break; case 2: SetPixelBlue(image,(Quantum) quantum,q); break; case 3: SetPixelAlpha(image,(Quantum) quantum,q); break; } n++; } p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelAlpha(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelAlpha(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } static void ImportRGBOQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 8: { unsigned char pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleCharToQuantum(pixel),q); p=PushCharPixel(p,&pixel); SetPixelOpacity(image,ScaleCharToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x++) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } switch (i) { case 0: SetPixelRed(image,(Quantum) quantum,q); break; case 1: SetPixelGreen(image,(Quantum) quantum,q); break; case 2: SetPixelBlue(image,(Quantum) quantum,q); break; case 3: SetPixelOpacity(image,(Quantum) quantum,q); break; } n++; } p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ScaleShortToQuantum((unsigned short) (pixel << 6)), q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushFloatPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelOpacity(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelRed(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGreen(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelBlue(image,ClampToQuantum(pixel),q); p=PushDoublePixel(quantum_info,p,&pixel); SetPixelOpacity(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } MagickExport size_t ImportQuantumPixels(const Image *image, CacheView *image_view,QuantumInfo *quantum_info, const QuantumType quantum_type,const unsigned char *magick_restrict pixels, ExceptionInfo *exception) { MagickSizeType number_pixels; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; size_t extent; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); if (pixels == (const unsigned char *) NULL) pixels=(const unsigned char *) GetQuantumPixels(quantum_info); x=0; p=pixels; if (image_view == (CacheView *) NULL) { number_pixels=GetImageExtent(image); q=GetAuthenticPixelQueue(image); } else { number_pixels=GetCacheViewExtent(image_view); q=GetCacheViewAuthenticPixelQueue(image_view); } ResetQuantumState(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); switch (quantum_type) { case AlphaQuantum: { ImportAlphaQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case BGRQuantum: { ImportBGRQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case BGRAQuantum: { ImportBGRAQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case BGROQuantum: { ImportBGROQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case BlackQuantum: { ImportBlackQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case BlueQuantum: case YellowQuantum: { ImportBlueQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case CMYKQuantum: { ImportCMYKQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case CMYKAQuantum: { ImportCMYKAQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case CMYKOQuantum: { ImportCMYKOQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case CbYCrYQuantum: { ImportCbYCrYQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case GrayQuantum: { ImportGrayQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case GrayAlphaQuantum: { ImportGrayAlphaQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case GreenQuantum: case MagentaQuantum: { ImportGreenQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case IndexQuantum: { ImportIndexQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case IndexAlphaQuantum: { ImportIndexAlphaQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case OpacityQuantum: { ImportOpacityQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case RedQuantum: case CyanQuantum: { ImportRedQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case RGBQuantum: case CbYCrQuantum: { ImportRGBQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case RGBAQuantum: case CbYCrAQuantum: { ImportRGBAQuantum(image,quantum_info,number_pixels,p,q,exception); break; } case RGBOQuantum: { ImportRGBOQuantum(image,quantum_info,number_pixels,p,q,exception); break; } default: break; } if ((quantum_type == CbYCrQuantum) || (quantum_type == CbYCrAQuantum)) { Quantum quantum; register Quantum *magick_restrict q; q=GetAuthenticPixelQueue(image); if (image_view != (CacheView *) NULL) q=GetCacheViewAuthenticPixelQueue(image_view); for (x=0; x < (ssize_t) number_pixels; x++) { quantum=GetPixelRed(image,q); SetPixelRed(image,GetPixelGreen(image,q),q); SetPixelGreen(image,quantum,q); q+=GetPixelChannels(image); } } if (quantum_info->alpha_type == DisassociatedQuantumAlpha) { double gamma, Sa; register Quantum *magick_restrict q; /* Disassociate alpha. */ q=GetAuthenticPixelQueue(image); if (image_view != (CacheView *) NULL) q=GetCacheViewAuthenticPixelQueue(image_view); for (x=0; x < (ssize_t) number_pixels; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } Sa=QuantumScale*GetPixelAlpha(image,q); gamma=PerceptibleReciprocal(Sa); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((channel == AlphaPixelChannel) || ((traits & UpdatePixelTrait) == 0)) continue; q[i]=ClampToQuantum(gamma*q[i]); } q+=GetPixelChannels(image); } } return(extent); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5314_0
crossvul-cpp_data_bad_3358_3
/* * IPV6 GSO/GRO offload support * Linux INET6 implementation * * 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. * * UDPv6 GSO support */ #include <linux/skbuff.h> #include <linux/netdevice.h> #include <net/protocol.h> #include <net/ipv6.h> #include <net/udp.h> #include <net/ip6_checksum.h> #include "ip6_offload.h" static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; unsigned int unfrag_ip6hlen, unfrag_len; struct frag_hdr *fptr; u8 *packet_start, *prevhdr; u8 nexthdr; u8 frag_hdr_sz = sizeof(struct frag_hdr); __wsum csum; int tnl_hlen; mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); /* Set the IPv6 fragment id if not set yet */ if (!skb_shinfo(skb)->ip6_frag_id) ipv6_proxy_select_ident(dev_net(skb->dev), skb); segs = NULL; goto out; } if (skb->encapsulation && skb_shinfo(skb)->gso_type & (SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM)) segs = skb_udp_tunnel_segment(skb, features, true); else { const struct ipv6hdr *ipv6h; struct udphdr *uh; if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto out; /* Do software UFO. Complete and fill in the UDP checksum as HW cannot * do checksum of UDP packets sent as multiple IP fragments. */ uh = udp_hdr(skb); ipv6h = ipv6_hdr(skb); uh->check = 0; csum = skb_checksum(skb, 0, skb->len, 0); uh->check = udp_v6_check(skb->len, &ipv6h->saddr, &ipv6h->daddr, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; skb->ip_summed = CHECKSUM_NONE; /* If there is no outer header we can fake a checksum offload * due to the fact that we have already done the checksum in * software prior to segmenting the frame. */ if (!skb->encap_hdr_csum) features |= NETIF_F_HW_CSUM; /* Check if there is enough headroom to insert fragment header. */ tnl_hlen = skb_tnl_header_len(skb); if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) { if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz)) goto out; } /* Find the unfragmentable header and shift it left by frag_hdr_sz * bytes to insert fragment header. */ unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; *prevhdr = NEXTHDR_FRAGMENT; unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) + unfrag_ip6hlen + tnl_hlen; packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset; memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len); SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz; skb->mac_header -= frag_hdr_sz; skb->network_header -= frag_hdr_sz; fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen); fptr->nexthdr = nexthdr; fptr->reserved = 0; if (!skb_shinfo(skb)->ip6_frag_id) ipv6_proxy_select_ident(dev_net(skb->dev), skb); fptr->identification = skb_shinfo(skb)->ip6_frag_id; /* Fragment the skb. ipv6 header and the remaining fields of the * fragment header are updated in ipv6_gso_segment() */ segs = skb_segment(skb, features); } out: return segs; } static struct sk_buff **udp6_gro_receive(struct sk_buff **head, struct sk_buff *skb) { struct udphdr *uh = udp_gro_udphdr(skb); if (unlikely(!uh)) goto flush; /* Don't bother verifying checksum if we're going to flush anyway. */ if (NAPI_GRO_CB(skb)->flush) goto skip; if (skb_gro_checksum_validate_zero_check(skb, IPPROTO_UDP, uh->check, ip6_gro_compute_pseudo)) goto flush; else if (uh->check) skb_gro_checksum_try_convert(skb, IPPROTO_UDP, uh->check, ip6_gro_compute_pseudo); skip: NAPI_GRO_CB(skb)->is_ipv6 = 1; return udp_gro_receive(head, skb, uh, udp6_lib_lookup_skb); flush: NAPI_GRO_CB(skb)->flush = 1; return NULL; } static int udp6_gro_complete(struct sk_buff *skb, int nhoff) { const struct ipv6hdr *ipv6h = ipv6_hdr(skb); struct udphdr *uh = (struct udphdr *)(skb->data + nhoff); if (uh->check) { skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL_CSUM; uh->check = ~udp_v6_check(skb->len - nhoff, &ipv6h->saddr, &ipv6h->daddr, 0); } else { skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL; } return udp_gro_complete(skb, nhoff, udp6_lib_lookup_skb); } static const struct net_offload udpv6_offload = { .callbacks = { .gso_segment = udp6_ufo_fragment, .gro_receive = udp6_gro_receive, .gro_complete = udp6_gro_complete, }, }; int udpv6_offload_init(void) { return inet6_add_offload(&udpv6_offload, IPPROTO_UDP); } int udpv6_offload_exit(void) { return inet6_del_offload(&udpv6_offload, IPPROTO_UDP); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3358_3
crossvul-cpp_data_bad_4232_0
/* ** $Id: lgc.c $ ** Garbage Collector ** See Copyright Notice in lua.h */ #define lgc_c #define LUA_CORE #include "lprefix.h" #include <stdio.h> #include <string.h> #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" /* ** Maximum number of elements to sweep in each single step. ** (Large enough to dissipate fixed overheads but small enough ** to allow small steps for the collector.) */ #define GCSWEEPMAX 100 /* ** Maximum number of finalizers to call in each single step. */ #define GCFINMAX 10 /* ** Cost of calling one finalizer. */ #define GCFINALIZECOST 50 /* ** The equivalent, in bytes, of one unit of "work" (visiting a slot, ** sweeping an object, etc.) */ #define WORK2MEM sizeof(TValue) /* ** macro to adjust 'pause': 'pause' is actually used like ** 'pause / PAUSEADJ' (value chosen by tests) */ #define PAUSEADJ 100 /* mask to erase all color bits (plus gen. related stuff) */ #define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS | AGEBITS)) /* macro to erase all color bits then sets only the current white bit */ #define makewhite(g,x) \ (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g))) #define white2gray(x) resetbits(x->marked, WHITEBITS) #define black2gray(x) resetbit(x->marked, BLACKBIT) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n))) #define checkconsistency(obj) \ lua_longassert(!iscollectable(obj) || righttt(obj)) /* ** Protected access to objects in values */ #define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL) #define markvalue(g,o) { checkconsistency(o); \ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } #define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); } #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } /* ** mark an object that can be NULL (either because it is really optional, ** or it was stripped as debug info, or inside an uncompleted structure) */ #define markobjectN(g,t) { if (t) markobject(g,t); } static void reallymarkobject (global_State *g, GCObject *o); static lu_mem atomic (lua_State *L); static void entersweep (lua_State *L); /* ** {====================================================== ** Generic functions ** ======================================================= */ /* ** one after last element in a hash array */ #define gnodelast(h) gnode(h, cast_sizet(sizenode(h))) static GCObject **getgclist (GCObject *o) { switch (o->tt) { case LUA_VTABLE: return &gco2t(o)->gclist; case LUA_VLCL: return &gco2lcl(o)->gclist; case LUA_VCCL: return &gco2ccl(o)->gclist; case LUA_VTHREAD: return &gco2th(o)->gclist; case LUA_VPROTO: return &gco2p(o)->gclist; case LUA_VUSERDATA: { Udata *u = gco2u(o); lua_assert(u->nuvalue > 0); return &u->gclist; } default: lua_assert(0); return 0; } } /* ** Link a collectable object 'o' with a known type into list pointed by 'p'. */ #define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o)) /* ** Link a generic collectable object 'o' into list pointed by 'p'. */ #define linkobjgclist(o,p) (*getgclist(o) = (p), (p) = obj2gco(o)) /* ** Clear keys for empty entries in tables. If entry is empty ** and its key is not marked, mark its entry as dead. This allows the ** collection of the key, but keeps its entry in the table (its removal ** could break a chain). The main feature of a dead key is that it must ** be different from any other value, to do not disturb searches. ** Other places never manipulate dead keys, because its associated empty ** value is enough to signal that the entry is logically empty. */ static void clearkey (Node *n) { lua_assert(isempty(gval(n))); if (keyiswhite(n)) setdeadkey(n); /* unused and unmarked key; remove it */ } /* ** tells whether a key or value can be cleared from a weak ** table. Non-collectable objects are never removed from weak ** tables. Strings behave as 'values', so are never removed too. for ** other objects: if really collected, cannot keep them; for objects ** being finalized, keep them in keys, but not in values */ static int iscleared (global_State *g, const GCObject *o) { if (o == NULL) return 0; /* non-collectable value */ else if (novariant(o->tt) == LUA_TSTRING) { markobject(g, o); /* strings are 'values', so are never weak */ return 0; } else return iswhite(o); } /* ** barrier that moves collector forward, that is, mark the white object ** 'v' being pointed by the black object 'o'. (If in sweep phase, clear ** the black object to white [sweep it] to avoid other barrier calls for ** this same object.) In the generational mode, 'v' must also become ** old, if 'o' is old; however, it cannot be changed directly to OLD, ** because it may still point to non-old objects. So, it is marked as ** OLD0. In the next cycle it will become OLD1, and in the next it ** will finally become OLD (regular old). */ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { global_State *g = G(L); lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); if (keepinvariant(g)) { /* must keep invariant? */ reallymarkobject(g, v); /* restore invariant */ if (isold(o)) { lua_assert(!isold(v)); /* white object could not be old */ setage(v, G_OLD0); /* restore generational invariant */ } } else { /* sweep phase */ lua_assert(issweepphase(g)); makewhite(g, o); /* mark main obj. as white to avoid other barriers */ } } /* ** barrier that moves collector backward, that is, mark the black object ** pointing to a white object as gray again. */ void luaC_barrierback_ (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(isblack(o) && !isdead(g, o)); lua_assert(g->gckind != KGC_GEN || (isold(o) && getage(o) != G_TOUCHED1)); if (getage(o) != G_TOUCHED2) /* not already in gray list? */ linkobjgclist(o, g->grayagain); /* link it in 'grayagain' */ black2gray(o); /* make object gray (again) */ setage(o, G_TOUCHED1); /* touched in current cycle */ } void luaC_fix (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ white2gray(o); /* they will be gray forever */ setage(o, G_OLD); /* and old forever */ g->allgc = o->next; /* remove object from 'allgc' list */ o->next = g->fixedgc; /* link it to 'fixedgc' list */ g->fixedgc = o; } /* ** create a new collectable object (with given type and size) and link ** it to 'allgc' list. */ GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) { global_State *g = G(L); GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz)); o->marked = luaC_white(g); o->tt = tt; o->next = g->allgc; g->allgc = o; return o; } /* }====================================================== */ /* ** {====================================================== ** Mark functions ** ======================================================= */ /* ** Mark an object. Userdata, strings, and closed upvalues are visited ** and turned black here. Other objects are marked gray and added ** to appropriate list to be visited (and turned black) later. (Open ** upvalues are already linked in 'headuv' list. They are kept gray ** to avoid barriers, as their values will be revisited by the thread.) */ static void reallymarkobject (global_State *g, GCObject *o) { white2gray(o); switch (o->tt) { case LUA_VSHRSTR: case LUA_VLNGSTR: { gray2black(o); break; } case LUA_VUPVAL: { UpVal *uv = gco2upv(o); if (!upisopen(uv)) /* open upvalues are kept gray */ gray2black(o); markvalue(g, uv->v); /* mark its content */ break; } case LUA_VUSERDATA: { Udata *u = gco2u(o); if (u->nuvalue == 0) { /* no user values? */ markobjectN(g, u->metatable); /* mark its metatable */ gray2black(o); /* nothing else to mark */ break; } /* else... */ } /* FALLTHROUGH */ case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE: case LUA_VTHREAD: case LUA_VPROTO: { linkobjgclist(o, g->gray); break; } default: lua_assert(0); break; } } /* ** mark metamethods for basic types */ static void markmt (global_State *g) { int i; for (i=0; i < LUA_NUMTAGS; i++) markobjectN(g, g->mt[i]); } /* ** mark all objects in list of being-finalized */ static lu_mem markbeingfnz (global_State *g) { GCObject *o; lu_mem count = 0; for (o = g->tobefnz; o != NULL; o = o->next) { count++; markobject(g, o); } return count; } /* ** Mark all values stored in marked open upvalues from non-marked threads. ** (Values from marked threads were already marked when traversing the ** thread.) Remove from the list threads that no longer have upvalues and ** not-marked threads. */ static int remarkupvals (global_State *g) { lua_State *thread; lua_State **p = &g->twups; int work = 0; while ((thread = *p) != NULL) { work++; lua_assert(!isblack(thread)); /* threads are never black */ if (isgray(thread) && thread->openupval != NULL) p = &thread->twups; /* keep marked thread with upvalues in the list */ else { /* thread is not marked or without upvalues */ UpVal *uv; *p = thread->twups; /* remove thread from the list */ thread->twups = thread; /* mark that it is out of list */ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { work++; if (!iswhite(uv)) /* upvalue already visited? */ markvalue(g, uv->v); /* mark its value */ } } } return work; } /* ** mark root set and reset all gray lists, to start a new collection */ static void restartcollection (global_State *g) { g->gray = g->grayagain = NULL; g->weak = g->allweak = g->ephemeron = NULL; markobject(g, g->mainthread); markvalue(g, &g->l_registry); markmt(g); markbeingfnz(g); /* mark any finalizing object left from previous cycle */ } /* }====================================================== */ /* ** {====================================================== ** Traverse functions ** ======================================================= */ /* ** Traverse a table with weak values and link it to proper list. During ** propagate phase, keep it in 'grayagain' list, to be revisited in the ** atomic phase. In the atomic phase, if table has any white value, ** put it in 'weak' list, to be cleared. */ static void traverseweakvalue (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); /* if there is array part, assume it may have white values (it is not worth traversing it now just to check) */ int hasclears = (h->alimit > 0); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */ hasclears = 1; /* table will have to be cleared */ } } if (g->gcstate == GCSatomic && hasclears) linkgclist(h, g->weak); /* has to be cleared later */ else linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ } /* ** Traverse an ephemeron table and link it to proper list. Returns true ** iff any object was marked during this traversal (which implies that ** convergence has to continue). During propagation phase, keep table ** in 'grayagain' list, to be visited again in the atomic phase. In ** the atomic phase, if table has any white->white entry, it has to ** be revisited during ephemeron convergence (as that key may turn ** black). Otherwise, if it has any white key, table has to be cleared ** (in the atomic phase). In generational mode, it (like all visited ** tables) must be kept in some gray list for post-processing. */ static int traverseephemeron (global_State *g, Table *h, int inv) { int marked = 0; /* true if an object is marked in this traversal */ int hasclears = 0; /* true if table has white keys */ int hasww = 0; /* true if table has entry "white-key -> white-value" */ unsigned int i; unsigned int asize = luaH_realasize(h); unsigned int nsize = sizenode(h); /* traverse array part */ for (i = 0; i < asize; i++) { if (valiswhite(&h->array[i])) { marked = 1; reallymarkobject(g, gcvalue(&h->array[i])); } } /* traverse hash part; if 'inv', traverse descending (see 'convergeephemerons') */ for (i = 0; i < nsize; i++) { Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i); if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */ hasclears = 1; /* table must be cleared */ if (valiswhite(gval(n))) /* value not marked yet? */ hasww = 1; /* white-white entry */ } else if (valiswhite(gval(n))) { /* value not marked yet? */ marked = 1; reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ } } /* link table into proper list */ if (g->gcstate == GCSpropagate) linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ else if (hasww) /* table has white->white entries? */ linkgclist(h, g->ephemeron); /* have to propagate again */ else if (hasclears) /* table has white keys? */ linkgclist(h, g->allweak); /* may have to clean white keys */ else if (g->gckind == KGC_GEN) linkgclist(h, g->grayagain); /* keep it in some list */ else gray2black(h); return marked; } static void traversestrongtable (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = luaH_realasize(h); for (i = 0; i < asize; i++) /* traverse array part */ markvalue(g, &h->array[i]); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); markvalue(g, gval(n)); } } if (g->gckind == KGC_GEN) { linkgclist(h, g->grayagain); /* keep it in some gray list */ black2gray(h); } } static lu_mem traversetable (global_State *g, Table *h) { const char *weakkey, *weakvalue; const TValue *mode = gfasttm(g, h->metatable, TM_MODE); markobjectN(g, h->metatable); if (mode && ttisstring(mode) && /* is there a weak mode? */ (cast_void(weakkey = strchr(svalue(mode), 'k')), cast_void(weakvalue = strchr(svalue(mode), 'v')), (weakkey || weakvalue))) { /* is really weak? */ black2gray(h); /* keep table gray */ if (!weakkey) /* strong keys? */ traverseweakvalue(g, h); else if (!weakvalue) /* strong values? */ traverseephemeron(g, h, 0); else /* all weak */ linkgclist(h, g->allweak); /* nothing to traverse now */ } else /* not weak */ traversestrongtable(g, h); return 1 + h->alimit + 2 * allocsizenode(h); } static int traverseudata (global_State *g, Udata *u) { int i; markobjectN(g, u->metatable); /* mark its metatable */ for (i = 0; i < u->nuvalue; i++) markvalue(g, &u->uv[i].uv); if (g->gckind == KGC_GEN) { linkgclist(u, g->grayagain); /* keep it in some gray list */ black2gray(u); } return 1 + u->nuvalue; } /* ** Traverse a prototype. (While a prototype is being build, its ** arrays can be larger than needed; the extra slots are filled with ** NULL, so the use of 'markobjectN') */ static int traverseproto (global_State *g, Proto *f) { int i; markobjectN(g, f->source); for (i = 0; i < f->sizek; i++) /* mark literals */ markvalue(g, &f->k[i]); for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ markobjectN(g, f->upvalues[i].name); for (i = 0; i < f->sizep; i++) /* mark nested protos */ markobjectN(g, f->p[i]); for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ markobjectN(g, f->locvars[i].varname); return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars; } static int traverseCclosure (global_State *g, CClosure *cl) { int i; for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ markvalue(g, &cl->upvalue[i]); return 1 + cl->nupvalues; } /* ** Traverse a Lua closure, marking its prototype and its upvalues. ** (Both can be NULL while closure is being created.) */ static int traverseLclosure (global_State *g, LClosure *cl) { int i; markobjectN(g, cl->p); /* mark its prototype */ for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */ UpVal *uv = cl->upvals[i]; markobjectN(g, uv); /* mark upvalue */ } return 1 + cl->nupvalues; } /* ** Traverse a thread, marking the elements in the stack up to its top ** and cleaning the rest of the stack in the final traversal. ** That ensures that the entire stack have valid (non-dead) objects. */ static int traversethread (global_State *g, lua_State *th) { UpVal *uv; StkId o = th->stack; if (o == NULL) return 1; /* stack not completely built yet */ lua_assert(g->gcstate == GCSatomic || th->openupval == NULL || isintwups(th)); for (; o < th->top; o++) /* mark live elements in the stack */ markvalue(g, s2v(o)); for (uv = th->openupval; uv != NULL; uv = uv->u.open.next) markobject(g, uv); /* open upvalues cannot be collected */ if (g->gcstate == GCSatomic) { /* final traversal? */ StkId lim = th->stack + th->stacksize; /* real end of stack */ for (; o < lim; o++) /* clear not-marked stack slice */ setnilvalue(s2v(o)); /* 'remarkupvals' may have removed thread from 'twups' list */ if (!isintwups(th) && th->openupval != NULL) { th->twups = g->twups; /* link it back to the list */ g->twups = th; } } else if (!g->gcemergency) luaD_shrinkstack(th); /* do not change stack in emergency cycle */ return 1 + th->stacksize; } /* ** traverse one gray object, turning it to black (except for threads, ** which are always gray). */ static lu_mem propagatemark (global_State *g) { GCObject *o = g->gray; gray2black(o); g->gray = *getgclist(o); /* remove from 'gray' list */ switch (o->tt) { case LUA_VTABLE: return traversetable(g, gco2t(o)); case LUA_VUSERDATA: return traverseudata(g, gco2u(o)); case LUA_VLCL: return traverseLclosure(g, gco2lcl(o)); case LUA_VCCL: return traverseCclosure(g, gco2ccl(o)); case LUA_VPROTO: return traverseproto(g, gco2p(o)); case LUA_VTHREAD: { lua_State *th = gco2th(o); linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ black2gray(o); return traversethread(g, th); } default: lua_assert(0); return 0; } } static lu_mem propagateall (global_State *g) { lu_mem tot = 0; while (g->gray) tot += propagatemark(g); return tot; } /* ** Traverse all ephemeron tables propagating marks from keys to values. ** Repeat until it converges, that is, nothing new is marked. 'dir' ** inverts the direction of the traversals, trying to speed up ** convergence on chains in the same table. ** */ static void convergeephemerons (global_State *g) { int changed; int dir = 0; do { GCObject *w; GCObject *next = g->ephemeron; /* get ephemeron list */ g->ephemeron = NULL; /* tables may return to this list when traversed */ changed = 0; while ((w = next) != NULL) { /* for each ephemeron table */ next = gco2t(w)->gclist; /* list is rebuilt during loop */ if (traverseephemeron(g, gco2t(w), dir)) { /* marked some value? */ propagateall(g); /* propagate changes */ changed = 1; /* will have to revisit all ephemeron tables */ } } dir = !dir; /* invert direction next time */ } while (changed); /* repeat until no more changes */ } /* }====================================================== */ /* ** {====================================================== ** Sweep Functions ** ======================================================= */ /* ** clear entries with unmarked keys from all weaktables in list 'l' */ static void clearbykeys (global_State *g, GCObject *l) { for (; l; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *limit = gnodelast(h); Node *n; for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gckeyN(n))) /* unmarked key? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } /* ** clear entries with unmarked values from all weaktables in list 'l' up ** to element 'f' */ static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) { for (; l != f; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = luaH_realasize(h); for (i = 0; i < asize; i++) { TValue *o = &h->array[i]; if (iscleared(g, gcvalueN(o))) /* value was collected? */ setempty(o); /* remove entry */ } for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } static void freeupval (lua_State *L, UpVal *uv) { if (upisopen(uv)) luaF_unlinkupval(uv); luaM_free(L, uv); } static void freeobj (lua_State *L, GCObject *o) { switch (o->tt) { case LUA_VPROTO: luaF_freeproto(L, gco2p(o)); break; case LUA_VUPVAL: freeupval(L, gco2upv(o)); break; case LUA_VLCL: luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues)); break; case LUA_VCCL: luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); break; case LUA_VTABLE: luaH_free(L, gco2t(o)); break; case LUA_VTHREAD: luaE_freethread(L, gco2th(o)); break; case LUA_VUSERDATA: { Udata *u = gco2u(o); luaM_freemem(L, o, sizeudata(u->nuvalue, u->len)); break; } case LUA_VSHRSTR: luaS_remove(L, gco2ts(o)); /* remove it from hash table */ luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen)); break; case LUA_VLNGSTR: luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen)); break; default: lua_assert(0); } } /* ** sweep at most 'countin' elements from a list of GCObjects erasing dead ** objects, where a dead object is one marked with the old (non current) ** white; change all non-dead objects back to white, preparing for next ** collection cycle. Return where to continue the traversal or NULL if ** list is finished. ('*countout' gets the number of elements traversed.) */ static GCObject **sweeplist (lua_State *L, GCObject **p, int countin, int *countout) { global_State *g = G(L); int ow = otherwhite(g); int i; int white = luaC_white(g); /* current white */ for (i = 0; *p != NULL && i < countin; i++) { GCObject *curr = *p; int marked = curr->marked; if (isdeadm(ow, marked)) { /* is 'curr' dead? */ *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* change mark to 'white' */ curr->marked = cast_byte((marked & maskcolors) | white); p = &curr->next; /* go to next element */ } } if (countout) *countout = i; /* number of elements traversed */ return (*p == NULL) ? NULL : p; } /* ** sweep a list until a live object (or end of list) */ static GCObject **sweeptolive (lua_State *L, GCObject **p) { GCObject **old = p; do { p = sweeplist(L, p, 1, NULL); } while (p == old); return p; } /* }====================================================== */ /* ** {====================================================== ** Finalization ** ======================================================= */ /* ** If possible, shrink string table. */ static void checkSizes (lua_State *L, global_State *g) { if (!g->gcemergency) { if (g->strt.nuse < g->strt.size / 4) { /* string table too big? */ l_mem olddebt = g->GCdebt; luaS_resize(L, g->strt.size / 2); g->GCestimate += g->GCdebt - olddebt; /* correct estimate */ } } } /* ** Get the next udata to be finalized from the 'tobefnz' list, and ** link it back into the 'allgc' list. */ static GCObject *udata2finalize (global_State *g) { GCObject *o = g->tobefnz; /* get first element */ lua_assert(tofinalize(o)); g->tobefnz = o->next; /* remove it from 'tobefnz' list */ o->next = g->allgc; /* return it to 'allgc' list */ g->allgc = o; resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ if (issweepphase(g)) makewhite(g, o); /* "sweep" object */ return o; } static void dothecall (lua_State *L, void *ud) { UNUSED(ud); luaD_callnoyield(L, L->top - 2, 0); } static void GCTM (lua_State *L) { global_State *g = G(L); const TValue *tm; TValue v; lua_assert(!g->gcemergency); setgcovalue(L, &v, udata2finalize(g)); tm = luaT_gettmbyobj(L, &v, TM_GC); if (!notm(tm)) { /* is there a finalizer? */ int status; lu_byte oldah = L->allowhook; int running = g->gcrunning; L->allowhook = 0; /* stop debug hooks during GC metamethod */ g->gcrunning = 0; /* avoid GC steps */ setobj2s(L, L->top++, tm); /* push finalizer... */ setobj2s(L, L->top++, &v); /* ... and its argument */ L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ L->allowhook = oldah; /* restore hooks */ g->gcrunning = running; /* restore state */ if (unlikely(status != LUA_OK)) { /* error while running __gc? */ luaE_warnerror(L, "__gc metamethod"); L->top--; /* pops error object */ } } } /* ** Call a few finalizers */ static int runafewfinalizers (lua_State *L, int n) { global_State *g = G(L); int i; for (i = 0; i < n && g->tobefnz; i++) GCTM(L); /* call one finalizer */ return i; } /* ** call all pending finalizers */ static void callallpendingfinalizers (lua_State *L) { global_State *g = G(L); while (g->tobefnz) GCTM(L); } /* ** find last 'next' field in list 'p' list (to add elements in its end) */ static GCObject **findlast (GCObject **p) { while (*p != NULL) p = &(*p)->next; return p; } /* ** Move all unreachable objects (or 'all' objects) that need ** finalization from list 'finobj' to list 'tobefnz' (to be finalized). ** (Note that objects after 'finobjold' cannot be white, so they ** don't need to be traversed. In incremental mode, 'finobjold' is NULL, ** so the whole list is traversed.) */ static void separatetobefnz (global_State *g, int all) { GCObject *curr; GCObject **p = &g->finobj; GCObject **lastnext = findlast(&g->tobefnz); while ((curr = *p) != g->finobjold) { /* traverse all finalizable objects */ lua_assert(tofinalize(curr)); if (!(iswhite(curr) || all)) /* not being collected? */ p = &curr->next; /* don't bother with it */ else { if (curr == g->finobjsur) /* removing 'finobjsur'? */ g->finobjsur = curr->next; /* correct it */ *p = curr->next; /* remove 'curr' from 'finobj' list */ curr->next = *lastnext; /* link at the end of 'tobefnz' list */ *lastnext = curr; lastnext = &curr->next; } } } /* ** if object 'o' has a finalizer, remove it from 'allgc' list (must ** search the list to find it) and link it in 'finobj' list. */ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { global_State *g = G(L); if (tofinalize(o) || /* obj. is already marked... */ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ return; /* nothing to be done */ else { /* move 'o' to 'finobj' list */ GCObject **p; if (issweepphase(g)) { makewhite(g, o); /* "sweep" object 'o' */ if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ } else { /* correct pointers into 'allgc' list, if needed */ if (o == g->survival) g->survival = o->next; if (o == g->old) g->old = o->next; if (o == g->reallyold) g->reallyold = o->next; } /* search for pointer pointing to 'o' */ for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } *p = o->next; /* remove 'o' from 'allgc' list */ o->next = g->finobj; /* link it in 'finobj' list */ g->finobj = o; l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ } } /* }====================================================== */ /* ** {====================================================== ** Generational Collector ** ======================================================= */ static void setpause (global_State *g); /* mask to erase all color bits, not changing gen-related stuff */ #define maskgencolors (~(bitmask(BLACKBIT) | WHITEBITS)) /* ** Sweep a list of objects, deleting dead ones and turning ** the non dead to old (without changing their colors). */ static void sweep2old (lua_State *L, GCObject **p) { GCObject *curr; while ((curr = *p) != NULL) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(isdead(G(L), curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* all surviving objects become old */ setage(curr, G_OLD); p = &curr->next; /* go to next element */ } } } /* ** Sweep for generational mode. Delete dead objects. (Because the ** collection is not incremental, there are no "new white" objects ** during the sweep. So, any white object must be dead.) For ** non-dead objects, advance their ages and clear the color of ** new objects. (Old objects keep their colors.) */ static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p, GCObject *limit) { static const lu_byte nextage[] = { G_SURVIVAL, /* from G_NEW */ G_OLD1, /* from G_SURVIVAL */ G_OLD1, /* from G_OLD0 */ G_OLD, /* from G_OLD1 */ G_OLD, /* from G_OLD (do not change) */ G_TOUCHED1, /* from G_TOUCHED1 (do not change) */ G_TOUCHED2 /* from G_TOUCHED2 (do not change) */ }; int white = luaC_white(g); GCObject *curr; while ((curr = *p) != limit) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(!isold(curr) && isdead(g, curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* correct mark and age */ if (getage(curr) == G_NEW) curr->marked = cast_byte((curr->marked & maskgencolors) | white); setage(curr, nextage[getage(curr)]); p = &curr->next; /* go to next element */ } } return p; } /* ** Traverse a list making all its elements white and clearing their ** age. */ static void whitelist (global_State *g, GCObject *p) { int white = luaC_white(g); for (; p != NULL; p = p->next) p->marked = cast_byte((p->marked & maskcolors) | white); } /* ** Correct a list of gray objects. ** Because this correction is done after sweeping, young objects might ** be turned white and still be in the list. They are only removed. ** For tables and userdata, advance 'touched1' to 'touched2'; 'touched2' ** objects become regular old and are removed from the list. ** For threads, just remove white ones from the list. */ static GCObject **correctgraylist (GCObject **p) { GCObject *curr; while ((curr = *p) != NULL) { switch (curr->tt) { case LUA_VTABLE: case LUA_VUSERDATA: { GCObject **next = getgclist(curr); if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */ lua_assert(isgray(curr)); gray2black(curr); /* make it black, for next barrier */ changeage(curr, G_TOUCHED1, G_TOUCHED2); p = next; /* go to next element */ } else { /* not touched in this cycle */ if (!iswhite(curr)) { /* not white? */ lua_assert(isold(curr)); if (getage(curr) == G_TOUCHED2) /* advance from G_TOUCHED2... */ changeage(curr, G_TOUCHED2, G_OLD); /* ... to G_OLD */ gray2black(curr); /* make it black */ } /* else, object is white: just remove it from this list */ *p = *next; /* remove 'curr' from gray list */ } break; } case LUA_VTHREAD: { lua_State *th = gco2th(curr); lua_assert(!isblack(th)); if (iswhite(th)) /* new object? */ *p = th->gclist; /* remove from gray list */ else /* old threads remain gray */ p = &th->gclist; /* go to next element */ break; } default: lua_assert(0); /* nothing more could be gray here */ } } return p; } /* ** Correct all gray lists, coalescing them into 'grayagain'. */ static void correctgraylists (global_State *g) { GCObject **list = correctgraylist(&g->grayagain); *list = g->weak; g->weak = NULL; list = correctgraylist(list); *list = g->allweak; g->allweak = NULL; list = correctgraylist(list); *list = g->ephemeron; g->ephemeron = NULL; correctgraylist(list); } /* ** Mark 'OLD1' objects when starting a new young collection. ** Gray objects are already in some gray list, and so will be visited ** in the atomic step. */ static void markold (global_State *g, GCObject *from, GCObject *to) { GCObject *p; for (p = from; p != to; p = p->next) { if (getage(p) == G_OLD1) { lua_assert(!iswhite(p)); if (isblack(p)) { black2gray(p); /* should be '2white', but gray works too */ reallymarkobject(g, p); } } } } /* ** Finish a young-generation collection. */ static void finishgencycle (lua_State *L, global_State *g) { correctgraylists(g); checkSizes(L, g); g->gcstate = GCSpropagate; /* skip restart */ if (!g->gcemergency) callallpendingfinalizers(L); } /* ** Does a young collection. First, mark 'OLD1' objects. (Only survival ** and "recent old" lists can contain 'OLD1' objects. New lists cannot ** contain 'OLD1' objects, at most 'OLD0' objects that were already ** visited when marked old.) Then does the atomic step. Then, ** sweep all lists and advance pointers. Finally, finish the collection. */ static void youngcollection (lua_State *L, global_State *g) { GCObject **psurvival; /* to point to first non-dead survival object */ lua_assert(g->gcstate == GCSpropagate); markold(g, g->survival, g->reallyold); markold(g, g->finobj, g->finobjrold); atomic(L); /* sweep nursery and get a pointer to its last live element */ psurvival = sweepgen(L, g, &g->allgc, g->survival); /* sweep 'survival' and 'old' */ sweepgen(L, g, psurvival, g->reallyold); g->reallyold = g->old; g->old = *psurvival; /* 'survival' survivals are old now */ g->survival = g->allgc; /* all news are survivals */ /* repeat for 'finobj' lists */ psurvival = sweepgen(L, g, &g->finobj, g->finobjsur); /* sweep 'survival' and 'old' */ sweepgen(L, g, psurvival, g->finobjrold); g->finobjrold = g->finobjold; g->finobjold = *psurvival; /* 'survival' survivals are old now */ g->finobjsur = g->finobj; /* all news are survivals */ sweepgen(L, g, &g->tobefnz, NULL); finishgencycle(L, g); } static void atomic2gen (lua_State *L, global_State *g) { /* sweep all elements making them old */ sweep2old(L, &g->allgc); /* everything alive now is old */ g->reallyold = g->old = g->survival = g->allgc; /* repeat for 'finobj' lists */ sweep2old(L, &g->finobj); g->finobjrold = g->finobjold = g->finobjsur = g->finobj; sweep2old(L, &g->tobefnz); g->gckind = KGC_GEN; g->lastatomic = 0; g->GCestimate = gettotalbytes(g); /* base for memory control */ finishgencycle(L, g); } /* ** Enter generational mode. Must go until the end of an atomic cycle ** to ensure that all threads and weak tables are in the gray lists. ** Then, turn all objects into old and finishes the collection. */ static lu_mem entergen (lua_State *L, global_State *g) { lu_mem numobjs; luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ numobjs = atomic(L); /* propagates all and then do the atomic stuff */ atomic2gen(L, g); return numobjs; } /* ** Enter incremental mode. Turn all objects white, make all ** intermediate lists point to NULL (to avoid invalid pointers), ** and go to the pause state. */ static void enterinc (global_State *g) { whitelist(g, g->allgc); g->reallyold = g->old = g->survival = NULL; whitelist(g, g->finobj); whitelist(g, g->tobefnz); g->finobjrold = g->finobjold = g->finobjsur = NULL; g->gcstate = GCSpause; g->gckind = KGC_INC; g->lastatomic = 0; } /* ** Change collector mode to 'newmode'. */ void luaC_changemode (lua_State *L, int newmode) { global_State *g = G(L); if (newmode != g->gckind) { if (newmode == KGC_GEN) /* entering generational mode? */ entergen(L, g); else enterinc(g); /* entering incremental mode */ } g->lastatomic = 0; } /* ** Does a full collection in generational mode. */ static lu_mem fullgen (lua_State *L, global_State *g) { enterinc(g); return entergen(L, g); } /* ** Set debt for the next minor collection, which will happen when ** memory grows 'genminormul'%. */ static void setminordebt (global_State *g) { luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul)); } /* ** Does a major collection after last collection was a "bad collection". ** ** When the program is building a big structure, it allocates lots of ** memory but generates very little garbage. In those scenarios, ** the generational mode just wastes time doing small collections, and ** major collections are frequently what we call a "bad collection", a ** collection that frees too few objects. To avoid the cost of switching ** between generational mode and the incremental mode needed for full ** (major) collections, the collector tries to stay in incremental mode ** after a bad collection, and to switch back to generational mode only ** after a "good" collection (one that traverses less than 9/8 objects ** of the previous one). ** The collector must choose whether to stay in incremental mode or to ** switch back to generational mode before sweeping. At this point, it ** does not know the real memory in use, so it cannot use memory to ** decide whether to return to generational mode. Instead, it uses the ** number of objects traversed (returned by 'atomic') as a proxy. The ** field 'g->lastatomic' keeps this count from the last collection. ** ('g->lastatomic != 0' also means that the last collection was bad.) */ static void stepgenfull (lua_State *L, global_State *g) { lu_mem newatomic; /* count of traversed objects */ lu_mem lastatomic = g->lastatomic; /* count from last collection */ if (g->gckind == KGC_GEN) /* still in generational mode? */ enterinc(g); /* enter incremental mode */ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ newatomic = atomic(L); /* mark everybody */ if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */ atomic2gen(L, g); /* return to generational mode */ setminordebt(g); } else { /* another bad collection; stay in incremental mode */ g->GCestimate = gettotalbytes(g); /* first estimate */; entersweep(L); luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ setpause(g); g->lastatomic = newatomic; } } /* ** Does a generational "step". ** Usually, this means doing a minor collection and setting the debt to ** make another collection when memory grows 'genminormul'% larger. ** ** However, there are exceptions. If memory grows 'genmajormul'% ** larger than it was at the end of the last major collection (kept ** in 'g->GCestimate'), the function does a major collection. At the ** end, it checks whether the major collection was able to free a ** decent amount of memory (at least half the growth in memory since ** previous major collection). If so, the collector keeps its state, ** and the next collection will probably be minor again. Otherwise, ** we have what we call a "bad collection". In that case, set the field ** 'g->lastatomic' to signal that fact, so that the next collection will ** go to 'stepgenfull'. ** ** 'GCdebt <= 0' means an explicit call to GC step with "size" zero; ** in that case, do a minor collection. */ static void genstep (lua_State *L, global_State *g) { if (g->lastatomic != 0) /* last collection was a bad one? */ stepgenfull(L, g); /* do a full step */ else { lu_mem majorbase = g->GCestimate; /* memory after last major collection */ lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul); if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) { lu_mem numobjs = fullgen(L, g); /* do a major collection */ if (gettotalbytes(g) < majorbase + (majorinc / 2)) { /* collected at least half of memory growth since last major collection; keep doing minor collections */ setminordebt(g); } else { /* bad collection */ g->lastatomic = numobjs; /* signal that last collection was bad */ setpause(g); /* do a long wait for next (major) collection */ } } else { /* regular case; do a minor collection */ youngcollection(L, g); setminordebt(g); g->GCestimate = majorbase; /* preserve base value */ } } lua_assert(isdecGCmodegen(g)); } /* }====================================================== */ /* ** {====================================================== ** GC control ** ======================================================= */ /* ** Set the "time" to wait before starting a new GC cycle; cycle will ** start when memory use hits the threshold of ('estimate' * pause / ** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero, ** because Lua cannot even start with less than PAUSEADJ bytes). */ static void setpause (global_State *g) { l_mem threshold, debt; int pause = getgcparam(g->gcpause); l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ lua_assert(estimate > 0); threshold = (pause < MAX_LMEM / estimate) /* overflow? */ ? estimate * pause /* no overflow */ : MAX_LMEM; /* overflow; truncate to maximum */ debt = gettotalbytes(g) - threshold; if (debt > 0) debt = 0; luaE_setdebt(g, debt); } /* ** Enter first sweep phase. ** The call to 'sweeptolive' makes the pointer point to an object ** inside the list (instead of to the header), so that the real sweep do ** not need to skip objects created between "now" and the start of the ** real sweep. */ static void entersweep (lua_State *L) { global_State *g = G(L); g->gcstate = GCSswpallgc; lua_assert(g->sweepgc == NULL); g->sweepgc = sweeptolive(L, &g->allgc); } /* ** Delete all objects in list 'p' until (but not including) object ** 'limit'. */ static void deletelist (lua_State *L, GCObject *p, GCObject *limit) { while (p != limit) { GCObject *next = p->next; freeobj(L, p); p = next; } } /* ** Call all finalizers of the objects in the given Lua state, and ** then free all objects, except for the main thread. */ void luaC_freeallobjects (lua_State *L) { global_State *g = G(L); luaC_changemode(L, KGC_INC); separatetobefnz(g, 1); /* separate all objects with finalizers */ lua_assert(g->finobj == NULL); callallpendingfinalizers(L); deletelist(L, g->allgc, obj2gco(g->mainthread)); deletelist(L, g->finobj, NULL); deletelist(L, g->fixedgc, NULL); /* collect fixed objects */ lua_assert(g->strt.nuse == 0); } static lu_mem atomic (lua_State *L) { global_State *g = G(L); lu_mem work = 0; GCObject *origweak, *origall; GCObject *grayagain = g->grayagain; /* save original list */ g->grayagain = NULL; lua_assert(g->ephemeron == NULL && g->weak == NULL); lua_assert(!iswhite(g->mainthread)); g->gcstate = GCSatomic; markobject(g, L); /* mark running thread */ /* registry and global metatables may be changed by API */ markvalue(g, &g->l_registry); markmt(g); /* mark global metatables */ work += propagateall(g); /* empties 'gray' list */ /* remark occasional upvalues of (maybe) dead threads */ work += remarkupvals(g); work += propagateall(g); /* propagate changes */ g->gray = grayagain; work += propagateall(g); /* traverse 'grayagain' list */ convergeephemerons(g); /* at this point, all strongly accessible objects are marked. */ /* Clear values from weak tables, before checking finalizers */ clearbyvalues(g, g->weak, NULL); clearbyvalues(g, g->allweak, NULL); origweak = g->weak; origall = g->allweak; separatetobefnz(g, 0); /* separate objects to be finalized */ work += markbeingfnz(g); /* mark objects that will be finalized */ work += propagateall(g); /* remark, to propagate 'resurrection' */ convergeephemerons(g); /* at this point, all resurrected objects are marked. */ /* remove dead objects from weak tables */ clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */ clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */ /* clear values from resurrected weak tables */ clearbyvalues(g, g->weak, origweak); clearbyvalues(g, g->allweak, origall); luaS_clearcache(g); g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ lua_assert(g->gray == NULL); return work; /* estimate of slots marked by 'atomic' */ } static int sweepstep (lua_State *L, global_State *g, int nextstate, GCObject **nextlist) { if (g->sweepgc) { l_mem olddebt = g->GCdebt; int count; g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count); g->GCestimate += g->GCdebt - olddebt; /* update estimate */ return count; } else { /* enter next state */ g->gcstate = nextstate; g->sweepgc = nextlist; return 0; /* no work done */ } } static lu_mem singlestep (lua_State *L) { global_State *g = G(L); switch (g->gcstate) { case GCSpause: { restartcollection(g); g->gcstate = GCSpropagate; return 1; } case GCSpropagate: { if (g->gray == NULL) { /* no more gray objects? */ g->gcstate = GCSenteratomic; /* finish propagate phase */ return 0; } else return propagatemark(g); /* traverse one gray object */ } case GCSenteratomic: { lu_mem work = atomic(L); /* work is what was traversed by 'atomic' */ entersweep(L); g->GCestimate = gettotalbytes(g); /* first estimate */; return work; } case GCSswpallgc: { /* sweep "regular" objects */ return sweepstep(L, g, GCSswpfinobj, &g->finobj); } case GCSswpfinobj: { /* sweep objects with finalizers */ return sweepstep(L, g, GCSswptobefnz, &g->tobefnz); } case GCSswptobefnz: { /* sweep objects to be finalized */ return sweepstep(L, g, GCSswpend, NULL); } case GCSswpend: { /* finish sweeps */ checkSizes(L, g); g->gcstate = GCScallfin; return 0; } case GCScallfin: { /* call remaining finalizers */ if (g->tobefnz && !g->gcemergency) { int n = runafewfinalizers(L, GCFINMAX); return n * GCFINALIZECOST; } else { /* emergency mode or no more finalizers */ g->gcstate = GCSpause; /* finish collection */ return 0; } } default: lua_assert(0); return 0; } } /* ** advances the garbage collector until it reaches a state allowed ** by 'statemask' */ void luaC_runtilstate (lua_State *L, int statesmask) { global_State *g = G(L); while (!testbit(statesmask, g->gcstate)) singlestep(L); } /* ** Performs a basic incremental step. The debt and step size are ** converted from bytes to "units of work"; then the function loops ** running single steps until adding that many units of work or ** finishing a cycle (pause state). Finally, it sets the debt that ** controls when next step will be performed. */ static void incstep (lua_State *L, global_State *g) { int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */ l_mem debt = (g->GCdebt / WORK2MEM) * stepmul; l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem)) ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul : MAX_LMEM; /* overflow; keep maximum value */ do { /* repeat until pause or enough "credit" (negative debt) */ lu_mem work = singlestep(L); /* perform one single step */ debt -= work; } while (debt > -stepsize && g->gcstate != GCSpause); if (g->gcstate == GCSpause) setpause(g); /* pause until next cycle */ else { debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */ luaE_setdebt(g, debt); } } /* ** performs a basic GC step if collector is running */ void luaC_step (lua_State *L) { global_State *g = G(L); lua_assert(!g->gcemergency); if (g->gcrunning) { /* running? */ if(isdecGCmodegen(g)) genstep(L, g); else incstep(L, g); } } /* ** Perform a full collection in incremental mode. ** Before running the collection, check 'keepinvariant'; if it is true, ** there may be some objects marked as black, so the collector has ** to sweep all objects to turn them back to white (as white has not ** changed, nothing will be collected). */ static void fullinc (lua_State *L, global_State *g) { if (keepinvariant(g)) /* black objects? */ entersweep(L); /* sweep everything to turn them back to white */ /* finish any pending sweep phase to start a new cycle */ luaC_runtilstate(L, bitmask(GCSpause)); luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */ /* estimate must be correct after a full GC cycle */ lua_assert(g->GCestimate == gettotalbytes(g)); luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ setpause(g); } /* ** Performs a full GC cycle; if 'isemergency', set a flag to avoid ** some operations which could change the interpreter state in some ** unexpected ways (running finalizers and shrinking some structures). */ void luaC_fullgc (lua_State *L, int isemergency) { global_State *g = G(L); lua_assert(!g->gcemergency); g->gcemergency = isemergency; /* set flag */ if (g->gckind == KGC_INC) fullinc(L, g); else fullgen(L, g); g->gcemergency = 0; } /* }====================================================== */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4232_0
crossvul-cpp_data_bad_3947_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Redirected Parallel Port Device Service * * Copyright 2010 O.S. Systems Software Ltda. * Copyright 2010 Eduardo Fiss Beloni <beloni@ossystems.com.br> * Copyright 2015 Thincast Technologies GmbH * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.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 <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <fcntl.h> #include <errno.h> #ifndef _WIN32 #include <termios.h> #include <strings.h> #include <sys/ioctl.h> #endif #ifdef __LINUX__ #include <linux/ppdev.h> #include <linux/parport.h> #endif #include <winpr/crt.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/stream.h> #include <winpr/collections.h> #include <winpr/interlocked.h> #include <freerdp/types.h> #include <freerdp/constants.h> #include <freerdp/channels/rdpdr.h> #include <freerdp/channels/log.h> #define TAG CHANNELS_TAG("drive.client") struct _PARALLEL_DEVICE { DEVICE device; int file; char* path; UINT32 id; HANDLE thread; wMessageQueue* queue; rdpContext* rdpcontext; }; typedef struct _PARALLEL_DEVICE PARALLEL_DEVICE; /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp) { char* path = NULL; int status; UINT32 PathLength; Stream_Seek(irp->input, 28); /* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */ /* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */ Stream_Read_UINT32(irp->input, PathLength); status = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2, &path, 0, NULL, NULL); if (status < 1) if (!(path = (char*)calloc(1, 1))) { WLog_ERR(TAG, "calloc failed!"); return CHANNEL_RC_NO_MEMORY; } parallel->id = irp->devman->id_sequence++; parallel->file = open(parallel->path, O_RDWR); if (parallel->file < 0) { irp->IoStatus = STATUS_ACCESS_DENIED; parallel->id = 0; } else { /* all read and write operations should be non-blocking */ if (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1) { } } Stream_Write_UINT32(irp->output, parallel->id); Stream_Write_UINT8(irp->output, 0); free(path); return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_process_irp_close(PARALLEL_DEVICE* parallel, IRP* irp) { if (close(parallel->file) < 0) { } else { } Stream_Zero(irp->output, 5); /* Padding(5) */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_process_irp_read(PARALLEL_DEVICE* parallel, IRP* irp) { UINT32 Length; UINT64 Offset; ssize_t status; BYTE* buffer = NULL; if (Stream_GetRemainingLength(irp->input) < 12) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, Length); Stream_Read_UINT64(irp->input, Offset); buffer = (BYTE*)malloc(Length); if (!buffer) { WLog_ERR(TAG, "malloc failed!"); return CHANNEL_RC_NO_MEMORY; } status = read(parallel->file, buffer, Length); if (status < 0) { irp->IoStatus = STATUS_UNSUCCESSFUL; free(buffer); buffer = NULL; Length = 0; } else { } Stream_Write_UINT32(irp->output, Length); if (Length > 0) { if (!Stream_EnsureRemainingCapacity(irp->output, Length)) { WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!"); free(buffer); return CHANNEL_RC_NO_MEMORY; } Stream_Write(irp->output, buffer, Length); } free(buffer); return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_process_irp_write(PARALLEL_DEVICE* parallel, IRP* irp) { UINT32 len; UINT32 Length; UINT64 Offset; ssize_t status; void* ptr; if (Stream_GetRemainingLength(irp->input) > 12) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, Length); Stream_Read_UINT64(irp->input, Offset); if (!Stream_SafeSeek(irp->input, 20)) /* Padding */ return ERROR_INVALID_DATA; ptr = Stream_Pointer(irp->input); if (!Stream_SafeSeek(irp->input, Length)) return ERROR_INVALID_DATA; len = Length; while (len > 0) { status = write(parallel->file, ptr, len); if (status < 0) { irp->IoStatus = STATUS_UNSUCCESSFUL; Length = 0; break; } Stream_Seek(irp->input, status); len -= status; } Stream_Write_UINT32(irp->output, Length); Stream_Write_UINT8(irp->output, 0); /* Padding */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_process_irp_device_control(PARALLEL_DEVICE* parallel, IRP* irp) { Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_process_irp(PARALLEL_DEVICE* parallel, IRP* irp) { UINT error; switch (irp->MajorFunction) { case IRP_MJ_CREATE: if ((error = parallel_process_irp_create(parallel, irp))) { WLog_ERR(TAG, "parallel_process_irp_create failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_CLOSE: if ((error = parallel_process_irp_close(parallel, irp))) { WLog_ERR(TAG, "parallel_process_irp_close failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_READ: if ((error = parallel_process_irp_read(parallel, irp))) { WLog_ERR(TAG, "parallel_process_irp_read failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_WRITE: if ((error = parallel_process_irp_write(parallel, irp))) { WLog_ERR(TAG, "parallel_process_irp_write failed with error %" PRIu32 "!", error); return error; } break; case IRP_MJ_DEVICE_CONTROL: if ((error = parallel_process_irp_device_control(parallel, irp))) { WLog_ERR(TAG, "parallel_process_irp_device_control failed with error %" PRIu32 "!", error); return error; } break; default: irp->IoStatus = STATUS_NOT_SUPPORTED; return irp->Complete(irp); break; } return CHANNEL_RC_OK; } static DWORD WINAPI parallel_thread_func(LPVOID arg) { IRP* irp; wMessage message; PARALLEL_DEVICE* parallel = (PARALLEL_DEVICE*)arg; UINT error = CHANNEL_RC_OK; while (1) { if (!MessageQueue_Wait(parallel->queue)) { WLog_ERR(TAG, "MessageQueue_Wait failed!"); error = ERROR_INTERNAL_ERROR; break; } if (!MessageQueue_Peek(parallel->queue, &message, TRUE)) { WLog_ERR(TAG, "MessageQueue_Peek failed!"); error = ERROR_INTERNAL_ERROR; break; } if (message.id == WMQ_QUIT) break; irp = (IRP*)message.wParam; if ((error = parallel_process_irp(parallel, irp))) { WLog_ERR(TAG, "parallel_process_irp failed with error %" PRIu32 "!", error); break; } } if (error && parallel->rdpcontext) setChannelError(parallel->rdpcontext, error, "parallel_thread_func reported an error"); ExitThread(error); return error; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_irp_request(DEVICE* device, IRP* irp) { PARALLEL_DEVICE* parallel = (PARALLEL_DEVICE*)device; if (!MessageQueue_Post(parallel->queue, NULL, 0, (void*)irp, NULL)) { WLog_ERR(TAG, "MessageQueue_Post failed!"); return ERROR_INTERNAL_ERROR; } return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT parallel_free(DEVICE* device) { UINT error; PARALLEL_DEVICE* parallel = (PARALLEL_DEVICE*)device; if (!MessageQueue_PostQuit(parallel->queue, 0) || (WaitForSingleObject(parallel->thread, INFINITE) == WAIT_FAILED)) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error); return error; } CloseHandle(parallel->thread); Stream_Free(parallel->device.data, TRUE); MessageQueue_Free(parallel->queue); free(parallel); return CHANNEL_RC_OK; } #ifdef BUILTIN_CHANNELS #define DeviceServiceEntry parallel_DeviceServiceEntry #else #define DeviceServiceEntry FREERDP_API DeviceServiceEntry #endif /** * Function description * * @return 0 on success, otherwise a Win32 error code */ UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints) { char* name; char* path; size_t i; size_t length; RDPDR_PARALLEL* device; PARALLEL_DEVICE* parallel; UINT error; device = (RDPDR_PARALLEL*)pEntryPoints->device; name = device->Name; path = device->Path; if (!name || (name[0] == '*') || !path) { /* TODO: implement auto detection of parallel ports */ return CHANNEL_RC_INITIALIZATION_ERROR; } if (name[0] && path[0]) { parallel = (PARALLEL_DEVICE*)calloc(1, sizeof(PARALLEL_DEVICE)); if (!parallel) { WLog_ERR(TAG, "calloc failed!"); return CHANNEL_RC_NO_MEMORY; } parallel->device.type = RDPDR_DTYP_PARALLEL; parallel->device.name = name; parallel->device.IRPRequest = parallel_irp_request; parallel->device.Free = parallel_free; parallel->rdpcontext = pEntryPoints->rdpcontext; length = strlen(name); parallel->device.data = Stream_New(NULL, length + 1); if (!parallel->device.data) { WLog_ERR(TAG, "Stream_New failed!"); error = CHANNEL_RC_NO_MEMORY; goto error_out; } for (i = 0; i <= length; i++) Stream_Write_UINT8(parallel->device.data, name[i] < 0 ? '_' : name[i]); parallel->path = path; parallel->queue = MessageQueue_New(NULL); if (!parallel->queue) { WLog_ERR(TAG, "MessageQueue_New failed!"); error = CHANNEL_RC_NO_MEMORY; goto error_out; } if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)parallel))) { WLog_ERR(TAG, "RegisterDevice failed with error %" PRIu32 "!", error); goto error_out; } if (!(parallel->thread = CreateThread(NULL, 0, parallel_thread_func, (void*)parallel, 0, NULL))) { WLog_ERR(TAG, "CreateThread failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } } return CHANNEL_RC_OK; error_out: MessageQueue_Free(parallel->queue); Stream_Free(parallel->device.data, TRUE); free(parallel); return error; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3947_0
crossvul-cpp_data_bad_2648_0
/* * Copyright (C) 1999 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_TCHECK2(tptr[0], 5); ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; ND_TCHECK2(tptr[0], 3); tlen = len; while (tlen >= 3) { type = *tptr; length = EXTRACT_16BITS(tptr+1); ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length - 3); switch (type) { case BGP_AIGP_TLV: ND_TCHECK2(tptr[3], 8); ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr+3))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr+3,"\n\t ", length-3); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2648_0
crossvul-cpp_data_bad_2754_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IPv6 routing header printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "ip6.h" #include "netdissect.h" #include "addrtoname.h" #include "extract.h" int rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_) { register const struct ip6_rthdr *dp; register const struct ip6_rthdr0 *dp0; register const u_char *ep; int i, len; register const struct in6_addr *addr; dp = (const struct ip6_rthdr *)bp; len = dp->ip6r_len; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; ND_TCHECK(dp->ip6r_segleft); ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/ ND_PRINT((ndo, ", type=%d", dp->ip6r_type)); ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft)); switch (dp->ip6r_type) { case IPV6_RTHDR_TYPE_0: case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */ dp0 = (const struct ip6_rthdr0 *)dp; ND_TCHECK(dp0->ip6r0_reserved); if (dp0->ip6r0_reserved || ndo->ndo_vflag) { ND_PRINT((ndo, ", rsv=0x%0x", EXTRACT_32BITS(&dp0->ip6r0_reserved))); } if (len % 2 == 1) goto trunc; len >>= 1; addr = &dp0->ip6r0_addr[0]; for (i = 0; i < len; i++) { if ((const u_char *)(addr + 1) > ep) goto trunc; ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr))); addr++; } /*(*/ ND_PRINT((ndo, ") ")); return((dp0->ip6r0_len + 1) << 3); break; default: goto trunc; break; } trunc: ND_PRINT((ndo, "[|srcrt]")); return -1; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2754_0
crossvul-cpp_data_good_2588_2
/* * hmp.c -- Midi Wavetable Processing library * * Copyright (C) WildMIDI Developers 2001-2016 * * This file is part of WildMIDI. * * WildMIDI is free software: you can redistribute and/or modify the player * under the terms of the GNU General Public License and you can redistribute * and/or modify the library under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either version 3 of * the licenses, or(at your option) any later version. * * WildMIDI 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 and * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License and the * GNU Lesser General Public License along with WildMIDI. If not, see * <http://www.gnu.org/licenses/>. */ #include "config.h" #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "common.h" #include "wm_error.h" #include "wildmidi_lib.h" #include "internal_midi.h" #include "reverb.h" #include "f_hmp.h" /* Turns hmp file data into an event stream */ struct _mdi * _WM_ParseNewHmp(uint8_t *hmp_data, uint32_t hmp_size) { uint8_t is_hmp2 = 0; uint32_t zero_cnt = 0; uint32_t i = 0; uint32_t hmp_file_length = 0; uint32_t hmp_chunks = 0; uint32_t hmp_divisions = 0; uint32_t hmp_unknown = 0; uint32_t hmp_bpm = 0; uint32_t hmp_song_time = 0; struct _mdi *hmp_mdi; uint8_t **hmp_chunk; uint32_t *chunk_length; uint32_t *chunk_ofs; uint32_t *chunk_delta; uint8_t *chunk_end; uint32_t chunk_num = 0; uint32_t hmp_track = 0; // uint32_t j = 0; uint32_t smallest_delta = 0; uint32_t subtract_delta = 0; // uint32_t chunks_finished = 0; uint32_t end_of_chunks = 0; uint32_t var_len_shift = 0; float tempo_f = 500000.0; float samples_per_delta_f = 0.0; // uint8_t hmp_event = 0; // uint8_t hmp_channel = 0; uint32_t sample_count = 0; float sample_count_f = 0; float sample_remainder = 0; if (memcmp(hmp_data, "HMIMIDIP", 8)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0); return NULL; } hmp_data += 8; hmp_size -= 8; if (!memcmp(hmp_data, "013195", 6)) { hmp_data += 6; hmp_size -= 6; is_hmp2 = 1; } // should be a bunch of \0's if (is_hmp2) { zero_cnt = 18; } else { zero_cnt = 24; } for (i = 0; i < zero_cnt; i++) { if (hmp_data[i] != 0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0); return NULL; } } hmp_data += zero_cnt; hmp_size -= zero_cnt; hmp_file_length = *hmp_data++; hmp_file_length += (*hmp_data++ << 8); hmp_file_length += (*hmp_data++ << 16); hmp_file_length += (*hmp_data++ << 24); hmp_size -= 4; UNUSED(hmp_file_length); // Next 12 bytes are normally \0 so skipping over them hmp_data += 12; hmp_size -= 12; hmp_chunks = *hmp_data++; hmp_chunks += (*hmp_data++ << 8); hmp_chunks += (*hmp_data++ << 16); hmp_chunks += (*hmp_data++ << 24); hmp_size -= 4; // Still decyphering what this is hmp_unknown = *hmp_data++; hmp_unknown += (*hmp_data++ << 8); hmp_unknown += (*hmp_data++ << 16); hmp_unknown += (*hmp_data++ << 24); hmp_size -= 4; UNUSED(hmp_unknown); // Defaulting: experimenting has found this to be the ideal value hmp_divisions = 60; // Beats per minute hmp_bpm = *hmp_data++; hmp_bpm += (*hmp_data++ << 8); hmp_bpm += (*hmp_data++ << 16); hmp_bpm += (*hmp_data++ << 24); hmp_size -= 4; /* Slow but needed for accuracy */ if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / hmp_bpm) + 0.5f; } else { tempo_f = (float) (60000000 / hmp_bpm); } samples_per_delta_f = _WM_GetSamplesPerTick(hmp_divisions, tempo_f); //DEBUG //fprintf(stderr, "DEBUG: Samples Per Delta Tick: %f\r\n",samples_per_delta_f); // FIXME: This value is incorrect hmp_song_time = *hmp_data++; hmp_song_time += (*hmp_data++ << 8); hmp_song_time += (*hmp_data++ << 16); hmp_song_time += (*hmp_data++ << 24); hmp_size -= 4; // DEBUG //fprintf(stderr,"DEBUG: ??DIVISIONS??: %u, BPM: %u, ??SONG TIME??: %u:%.2u\r\n",hmp_divisions, hmp_bpm, (hmp_song_time / 60), (hmp_song_time % 60)); UNUSED(hmp_song_time); if (is_hmp2) { hmp_data += 840; hmp_size -= 840; } else { hmp_data += 712; hmp_size -= 712; } hmp_mdi = _WM_initMDI(); _WM_midi_setup_divisions(hmp_mdi, hmp_divisions); _WM_midi_setup_tempo(hmp_mdi, (uint32_t)tempo_f); hmp_chunk = malloc(sizeof(uint8_t *) * hmp_chunks); chunk_length = malloc(sizeof(uint32_t) * hmp_chunks); chunk_delta = malloc(sizeof(uint32_t) * hmp_chunks); chunk_ofs = malloc(sizeof(uint32_t) * hmp_chunks); chunk_end = malloc(sizeof(uint8_t) * hmp_chunks); smallest_delta = 0xffffffff; // store chunk info for use, and check chunk lengths for (i = 0; i < hmp_chunks; i++) { hmp_chunk[i] = hmp_data; chunk_ofs[i] = 0; chunk_num = *hmp_data++; chunk_num += (*hmp_data++ << 8); chunk_num += (*hmp_data++ << 16); chunk_num += (*hmp_data++ << 24); chunk_ofs[i] += 4; UNUSED(chunk_num); chunk_length[i] = *hmp_data++; chunk_length[i] += (*hmp_data++ << 8); chunk_length[i] += (*hmp_data++ << 16); chunk_length[i] += (*hmp_data++ << 24); chunk_ofs[i] += 4; if (chunk_length[i] > hmp_size) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0); goto _hmp_end; } hmp_size -= chunk_length[i]; hmp_track = *hmp_data++; hmp_track += (*hmp_data++ << 8); hmp_track += (*hmp_data++ << 16); hmp_track += (*hmp_data++ << 24); chunk_ofs[i] += 4; UNUSED(hmp_track); // Start of Midi Data chunk_delta[i] = 0; var_len_shift = 0; if (*hmp_data < 0x80) { do { chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift); var_len_shift += 7; chunk_ofs[i]++; } while (*hmp_data < 0x80); } chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift); chunk_ofs[i]++; if (chunk_delta[i] < smallest_delta) { smallest_delta = chunk_delta[i]; } // goto start of next chunk hmp_data = hmp_chunk[i] + chunk_length[i]; chunk_length[i] -= chunk_ofs[i]; hmp_chunk[i] += chunk_ofs[i]++; chunk_end[i] = 0; } subtract_delta = smallest_delta; sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count; hmp_mdi->extra_info.approx_total_samples += sample_count; while (end_of_chunks < hmp_chunks) { smallest_delta = 0; // DEBUG // fprintf(stderr,"DEBUG: Delta Ticks: %u\r\n",subtract_delta); for (i = 0; i < hmp_chunks; i++) { if (chunk_end[i]) continue; if (chunk_delta[i]) { chunk_delta[i] -= subtract_delta; if (chunk_delta[i]) { if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) { smallest_delta = chunk_delta[i]; } continue; } } do { if (((hmp_chunk[i][0] & 0xf0) == 0xb0 ) && ((hmp_chunk[i][1] == 110) || (hmp_chunk[i][1] == 111)) && (hmp_chunk[i][2] > 0x7f)) { // Reserved for loop markers // TODO: still deciding what to do about these hmp_chunk[i] += 3; chunk_length[i] -= 3; } else { uint32_t setup_ret = 0; if ((setup_ret = _WM_SetupMidiEvent(hmp_mdi, hmp_chunk[i], chunk_length[i], 0)) == 0) { goto _hmp_end; } if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x2f) && (hmp_chunk[i][2] == 0x00)) { /* End of Chunk */ end_of_chunks++; chunk_end[i] = 1; chunk_length[i] -= 3; hmp_chunk[i] += 3; goto NEXT_CHUNK; } else if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x51) && (hmp_chunk[i][2] == 0x03)) { /* Tempo */ tempo_f = (float)((hmp_chunk[i][3] << 16) + (hmp_chunk[i][4] << 8)+ hmp_chunk[i][5]); if (tempo_f == 0.0) tempo_f = 500000.0; // DEBUG fprintf(stderr,"DEBUG: Tempo change %f\r\n", tempo_f); } hmp_chunk[i] += setup_ret; chunk_length[i] -= setup_ret; } var_len_shift = 0; chunk_delta[i] = 0; if (chunk_length[i] && *hmp_chunk[i] < 0x80) { do { if (! chunk_length[i]) break; chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift); var_len_shift += 7; hmp_chunk[i]++; chunk_length[i]--; } while (*hmp_chunk[i] < 0x80); } if (! chunk_length[i]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0); goto _hmp_end; } chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift); hmp_chunk[i]++; chunk_length[i]--; } while (!chunk_delta[i]); if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) { smallest_delta = chunk_delta[i]; } NEXT_CHUNK: continue; } subtract_delta = smallest_delta; sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count; hmp_mdi->extra_info.approx_total_samples += sample_count; // DEBUG // fprintf(stderr,"DEBUG: Sample Count %u\r\n",sample_count); } if ((hmp_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _hmp_end; } hmp_mdi->extra_info.current_sample = 0; hmp_mdi->current_event = &hmp_mdi->events[0]; hmp_mdi->samples_to_mix = 0; hmp_mdi->note = NULL; _WM_ResetToStart(hmp_mdi); _hmp_end: free(hmp_chunk); free(chunk_length); free(chunk_delta); free(chunk_ofs); free(chunk_end); if (hmp_mdi->reverb) return (hmp_mdi); _WM_freeMDI(hmp_mdi); return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2588_2
crossvul-cpp_data_bad_486_0
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. ASN.1 utility functions Copyright 2012-2017 Henrik Andersson <hean01@cendio.se> for Cendio AB 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 3 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 "rdesktop.h" /* Parse an ASN.1 BER header */ RD_BOOL ber_parse_header(STREAM s, int tagval, int *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); } void ber_out_sequence(STREAM out, STREAM content) { size_t length; length = (content ? s_length(content) : 0); ber_out_header(out, BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, length); if (content) out_stream(out, content); } /* Output an ASN.1 BER header */ void ber_out_header(STREAM s, int tagval, int length) { if (tagval > 0xff) { out_uint16_be(s, tagval); } else { out_uint8(s, tagval); } if (length >= 0x80) { out_uint8(s, 0x82); out_uint16_be(s, length); } else out_uint8(s, length); } /* Output an ASN.1 BER integer */ void ber_out_integer(STREAM s, int value) { ber_out_header(s, BER_TAG_INTEGER, 2); out_uint16_be(s, value); } RD_BOOL ber_in_header(STREAM s, int *tagval, int *decoded_len) { in_uint8(s, *tagval); in_uint8(s, *decoded_len); if (*decoded_len < 0x80) return True; else if (*decoded_len == 0x81) { in_uint8(s, *decoded_len); return True; } else if (*decoded_len == 0x82) { in_uint16_be(s, *decoded_len); return True; } return False; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_0
crossvul-cpp_data_good_2682_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Apple's DLT_PKTAP printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #ifdef DLT_PKTAP /* * XXX - these are little-endian in the captures I've seen, but Apple * no longer make any big-endian machines (Macs use x86, iOS machines * use ARM and run it little-endian), so that might be by definition * or they might be host-endian. * * If a big-endian PKTAP file ever shows up, and it comes from a * big-endian machine, presumably these are host-endian, and we need * to just fetch the fields directly in tcpdump but byte-swap them * to host byte order in libpcap. */ typedef struct pktap_header { uint32_t pkt_len; /* length of pktap header */ uint32_t pkt_rectype; /* type of record */ uint32_t pkt_dlt; /* DLT type of this packet */ char pkt_ifname[24]; /* interface name */ uint32_t pkt_flags; uint32_t pkt_pfamily; /* "protocol family" */ uint32_t pkt_llhdrlen; /* link-layer header length? */ uint32_t pkt_lltrlrlen; /* link-layer trailer length? */ uint32_t pkt_pid; /* process ID */ char pkt_cmdname[20]; /* command name */ uint32_t pkt_svc_class; /* "service class" */ uint16_t pkt_iftype; /* "interface type" */ uint16_t pkt_ifunit; /* unit number of interface? */ uint32_t pkt_epid; /* "effective process ID" */ char pkt_ecmdname[20]; /* "effective command name" */ } pktap_header_t; /* * Record types. */ #define PKT_REC_NONE 0 /* nothing follows the header */ #define PKT_REC_PACKET 1 /* a packet follows the header */ static inline void pktap_header_print(netdissect_options *ndo, const u_char *bp, u_int length) { const pktap_header_t *hdr; uint32_t dlt, hdrlen; const char *dltname; hdr = (const pktap_header_t *)bp; dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt); hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len); dltname = pcap_datalink_val_to_name(dlt); if (!ndo->ndo_qflag) { ND_PRINT((ndo,"DLT %s (%d) len %d", (dltname != NULL ? dltname : "UNKNOWN"), dlt, hdrlen)); } else { ND_PRINT((ndo,"%s", (dltname != NULL ? dltname : "UNKNOWN"))); } ND_PRINT((ndo, ", length %u: ", length)); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->ts' is the timestamp, * 'h->len' is the length of the packet off the wire, and 'h->caplen' * is the number of bytes actually captured. */ u_int pktap_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { uint32_t dlt, hdrlen, rectype; u_int caplen = h->caplen; u_int length = h->len; if_printer printer; const pktap_header_t *hdr; struct pcap_pkthdr nhdr; if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) { ND_PRINT((ndo, "[|pktap]")); return (0); } hdr = (const pktap_header_t *)p; dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt); hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len); if (hdrlen < sizeof(pktap_header_t)) { /* * Claimed header length < structure length. * XXX - does this just mean some fields aren't * being supplied, or is it truly an error (i.e., * is the length supplied so that the header can * be expanded in the future)? */ ND_PRINT((ndo, "[|pktap]")); return (0); } if (caplen < hdrlen || length < hdrlen) { ND_PRINT((ndo, "[|pktap]")); return (hdrlen); } if (ndo->ndo_eflag) pktap_header_print(ndo, p, length); length -= hdrlen; caplen -= hdrlen; p += hdrlen; rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype); switch (rectype) { case PKT_REC_NONE: ND_PRINT((ndo, "no data")); break; case PKT_REC_PACKET: if ((printer = lookup_printer(dlt)) != NULL) { nhdr = *h; nhdr.caplen = caplen; nhdr.len = length; hdrlen += printer(ndo, &nhdr, p); } else { if (!ndo->ndo_eflag) pktap_header_print(ndo, (const u_char *)hdr, length + hdrlen); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); } break; } return (hdrlen); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */ #endif /* DLT_PKTAP */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2682_0
crossvul-cpp_data_good_5313_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-1); 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); p++; q+=GetPixelChannels(image); } 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); } } } } 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); } } } } 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=0; 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-125/c/good_5313_0
crossvul-cpp_data_bad_5239_2
/** * Test that the crafted TGA file doesn't trigger OOB reads. */ #include "gd.h" #include "gdtest.h" static size_t read_test_file(char **buffer, char *basename); int main() { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, "heap_overflow.tga"); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); return gdNumFailures(); } static size_t read_test_file(char **buffer, char *basename) { char *filename; FILE *fp; size_t exp_size, act_size; filename = gdTestFilePath2("tga", basename); fp = fopen(filename, "rb"); gdTestAssert(fp != NULL); fseek(fp, 0, SEEK_END); exp_size = ftell(fp); fseek(fp, 0, SEEK_SET); *buffer = malloc(exp_size); gdTestAssert(*buffer != NULL); act_size = fread(*buffer, sizeof(**buffer), exp_size, fp); gdTestAssert(act_size == exp_size); fclose(fp); free(filename); return act_size; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5239_2
crossvul-cpp_data_good_3209_1
/* * Yerase's TNEF Stream Reader Library * Copyright (C) 2003 Randall E. Hand * * 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 * * You can contact me at randall.hand@gmail.com for questions or assistance */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <limits.h> #include "ytnef.h" #include "tnef-errors.h" #include "mapi.h" #include "mapidefs.h" #include "mapitags.h" #include "config.h" #define RTF_PREBUF "{\\rtf1\\ansi\\mac\\deff0\\deftab720{\\fonttbl;}{\\f0\\fnil \\froman \\fswiss \\fmodern \\fscript \\fdecor MS Sans SerifSymbolArialTimes New RomanCourier{\\colortbl\\red0\\green0\\blue0\n\r\\par \\pard\\plain\\f0\\fs20\\b\\i\\u\\tab\\tx" #define DEBUG(lvl, curlvl, msg) \ if ((lvl) >= (curlvl)) \ printf("DEBUG(%i/%i): %s\n", curlvl, lvl, msg); #define DEBUG1(lvl, curlvl, msg, var1) \ if ((lvl) >= (curlvl)) { \ printf("DEBUG(%i/%i):", curlvl, lvl); \ printf(msg, var1); \ printf("\n"); \ } #define DEBUG2(lvl, curlvl, msg, var1, var2) \ if ((lvl) >= (curlvl)) { \ printf("DEBUG(%i/%i):", curlvl, lvl); \ printf(msg, var1, var2); \ printf("\n"); \ } #define DEBUG3(lvl, curlvl, msg, var1, var2, var3) \ if ((lvl) >= (curlvl)) { \ printf("DEBUG(%i/%i):", curlvl, lvl); \ printf(msg, var1, var2,var3); \ printf("\n"); \ } #define MIN(x,y) (((x)<(y))?(x):(y)) #define ALLOCCHECK(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(-1); } } #define ALLOCCHECK_CHAR(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(NULL); } } #define SIZECHECK(x) { if ((((char *)d - (char *)data) + x) > size) { printf("Corrupted file detected at %s : %i\n", __FILE__, __LINE__); return(-1); } } int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p); void SetFlip(void); int TNEFDefaultHandler STD_ARGLIST; int TNEFAttachmentFilename STD_ARGLIST; int TNEFAttachmentSave STD_ARGLIST; int TNEFDetailedPrint STD_ARGLIST; int TNEFHexBreakdown STD_ARGLIST; int TNEFBody STD_ARGLIST; int TNEFRendData STD_ARGLIST; int TNEFDateHandler STD_ARGLIST; int TNEFPriority STD_ARGLIST; int TNEFVersion STD_ARGLIST; int TNEFMapiProperties STD_ARGLIST; int TNEFIcon STD_ARGLIST; int TNEFSubjectHandler STD_ARGLIST; int TNEFFromHandler STD_ARGLIST; int TNEFRecipTable STD_ARGLIST; int TNEFAttachmentMAPI STD_ARGLIST; int TNEFSentFor STD_ARGLIST; int TNEFMessageClass STD_ARGLIST; int TNEFMessageID STD_ARGLIST; int TNEFParentID STD_ARGLIST; int TNEFOriginalMsgClass STD_ARGLIST; int TNEFCodePage STD_ARGLIST; BYTE *TNEFFileContents = NULL; DWORD TNEFFileContentsSize; BYTE *TNEFFileIcon = NULL; DWORD TNEFFileIconSize; int IsCompressedRTF(variableLength *p); TNEFHandler TNEFList[] = { {attNull, "Null", TNEFDefaultHandler}, {attFrom, "From", TNEFFromHandler}, {attSubject, "Subject", TNEFSubjectHandler}, {attDateSent, "Date Sent", TNEFDateHandler}, {attDateRecd, "Date Received", TNEFDateHandler}, {attMessageStatus, "Message Status", TNEFDefaultHandler}, {attMessageClass, "Message Class", TNEFMessageClass}, {attMessageID, "Message ID", TNEFMessageID}, {attParentID, "Parent ID", TNEFParentID}, {attConversationID, "Conversation ID", TNEFDefaultHandler}, {attBody, "Body", TNEFBody}, {attPriority, "Priority", TNEFPriority}, {attAttachData, "Attach Data", TNEFAttachmentSave}, {attAttachTitle, "Attach Title", TNEFAttachmentFilename}, {attAttachMetaFile, "Attach Meta-File", TNEFIcon}, {attAttachCreateDate, "Attachment Create Date", TNEFDateHandler}, {attAttachModifyDate, "Attachment Modify Date", TNEFDateHandler}, {attDateModified, "Date Modified", TNEFDateHandler}, {attAttachTransportFilename, "Attachment Transport name", TNEFDefaultHandler}, {attAttachRenddata, "Attachment Display info", TNEFRendData}, {attMAPIProps, "MAPI Properties", TNEFMapiProperties}, {attRecipTable, "Recip Table", TNEFRecipTable}, {attAttachment, "Attachment", TNEFAttachmentMAPI}, {attTnefVersion, "TNEF Version", TNEFVersion}, {attOemCodepage, "OEM CodePage", TNEFCodePage}, {attOriginalMessageClass, "Original Message Class", TNEFOriginalMsgClass}, {attOwner, "Owner", TNEFDefaultHandler}, {attSentFor, "Sent For", TNEFSentFor}, {attDelegate, "Delegate", TNEFDefaultHandler}, {attDateStart, "Date Start", TNEFDateHandler}, {attDateEnd, "Date End", TNEFDateHandler}, {attAidOwner, "Aid Owner", TNEFDefaultHandler}, {attRequestRes, "Request Response", TNEFDefaultHandler} }; WORD SwapWord(BYTE *p, int size) { union BYTES2WORD { WORD word; BYTE bytes[sizeof(WORD)]; }; union BYTES2WORD converter; converter.word = 0; int i = 0; int correct = size > sizeof(WORD) ? sizeof(WORD) : size; #ifdef WORDS_BIGENDIAN for (i = 0; i < correct; ++i) { converter.bytes[i] = p[correct - i]; } #else for (i = 0; i < correct; ++i) { converter.bytes[i] = p[i]; } #endif return converter.word; } DWORD SwapDWord(BYTE *p, int size) { union BYTES2DWORD { DWORD dword; BYTE bytes[sizeof(DWORD)]; }; union BYTES2DWORD converter; converter.dword = 0; int i = 0; int correct = size > sizeof(DWORD) ? sizeof(DWORD) : size; #ifdef WORDS_BIGENDIAN for (i = 0; i < correct; ++i) { converter.bytes[i] = p[correct - i]; } #else for (i = 0; i < correct; ++i) { converter.bytes[i] = p[i]; } #endif return converter.dword; } DDWORD SwapDDWord(BYTE *p, int size) { union BYTES2DDWORD { DDWORD ddword; BYTE bytes[sizeof(DDWORD)]; }; union BYTES2DDWORD converter; converter.ddword = 0; int i = 0; int correct = size > sizeof(DDWORD) ? sizeof(DDWORD) : size; #ifdef WORDS_BIGENDIAN for (i = 0; i < correct; ++i) { converter.bytes[i] = p[correct - i]; } #else for (i = 0; i < correct; ++i) { converter.bytes[i] = p[i]; } #endif return converter.ddword; } /* convert 16-bit unicode to UTF8 unicode */ char *to_utf8(size_t len, char *buf) { int i, j = 0; /* worst case length */ if (len > 10000) { // deal with this by adding an arbitrary limit printf("suspecting a corrupt file in UTF8 conversion\n"); exit(-1); } char *utf8 = malloc(3 * len / 2 + 1); for (i = 0; i < len - 1; i += 2) { unsigned int c = SwapWord((BYTE *)buf + i, 2); if (c <= 0x007f) { utf8[j++] = 0x00 | ((c & 0x007f) >> 0); } else if (c < 0x07ff) { utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6); utf8[j++] = 0x80 | ((c & 0x003f) >> 0); } else { utf8[j++] = 0xe0 | ((c & 0xf000) >> 12); utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6); utf8[j++] = 0x80 | ((c & 0x003f) >> 0); } } /* just in case the original was not null terminated */ utf8[j++] = '\0'; return utf8; } // ----------------------------------------------------------------------------- int TNEFDefaultHandler STD_ARGLIST { if (TNEF->Debug >= 1) printf("%s: [%i] %s\n", TNEFList[id].name, size, data); return 0; } // ----------------------------------------------------------------------------- int TNEFCodePage STD_ARGLIST { TNEF->CodePage.size = size; TNEF->CodePage.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->CodePage.data); memcpy(TNEF->CodePage.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFParentID STD_ARGLIST { memcpy(TNEF->parentID, data, MIN(size, sizeof(TNEF->parentID))); return 0; } // ----------------------------------------------------------------------------- int TNEFMessageID STD_ARGLIST { memcpy(TNEF->messageID, data, MIN(size, sizeof(TNEF->messageID))); return 0; } // ----------------------------------------------------------------------------- int TNEFBody STD_ARGLIST { TNEF->body.size = size; TNEF->body.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->body.data); memcpy(TNEF->body.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFOriginalMsgClass STD_ARGLIST { TNEF->OriginalMessageClass.size = size; TNEF->OriginalMessageClass.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->OriginalMessageClass.data); memcpy(TNEF->OriginalMessageClass.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFMessageClass STD_ARGLIST { memcpy(TNEF->messageClass, data, MIN(size, sizeof(TNEF->messageClass))); return 0; } // ----------------------------------------------------------------------------- int TNEFFromHandler STD_ARGLIST { TNEF->from.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->from.data); TNEF->from.size = size; memcpy(TNEF->from.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFSubjectHandler STD_ARGLIST { if (TNEF->subject.data) free(TNEF->subject.data); TNEF->subject.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->subject.data); TNEF->subject.size = size; memcpy(TNEF->subject.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFRendData STD_ARGLIST { Attachment *p; // Find the last attachment. p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; // Add a new one p->next = calloc(1, sizeof(Attachment)); ALLOCCHECK(p->next); p = p->next; TNEFInitAttachment(p); int correct = (size >= sizeof(renddata)) ? sizeof(renddata) : size; memcpy(&(p->RenderData), data, correct); return 0; } // ----------------------------------------------------------------------------- int TNEFVersion STD_ARGLIST { WORD major; WORD minor; minor = SwapWord((BYTE*)data, size); major = SwapWord((BYTE*)data + 2, size - 2); snprintf(TNEF->version, sizeof(TNEF->version), "TNEF%i.%i", major, minor); return 0; } // ----------------------------------------------------------------------------- int TNEFIcon STD_ARGLIST { Attachment *p; // Find the last attachment. p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; p->IconData.size = size; p->IconData.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(p->IconData.data); memcpy(p->IconData.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFRecipTable STD_ARGLIST { DWORD count; BYTE *d; int current_row; int propcount; int current_prop; d = (BYTE*)data; count = SwapDWord((BYTE*)d, 4); d += 4; // printf("Recipient Table containing %u rows\n", count); return 0; for (current_row = 0; current_row < count; current_row++) { propcount = SwapDWord((BYTE*)d, 4); if (TNEF->Debug >= 1) printf("> Row %i contains %i properties\n", current_row, propcount); d += 4; for (current_prop = 0; current_prop < propcount; current_prop++) { } } return 0; } // ----------------------------------------------------------------------------- int TNEFAttachmentMAPI STD_ARGLIST { Attachment *p; // Find the last attachment. // p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; return TNEFFillMapi(TNEF, (BYTE*)data, size, &(p->MAPI)); } // ----------------------------------------------------------------------------- int TNEFMapiProperties STD_ARGLIST { if (TNEFFillMapi(TNEF, (BYTE*)data, size, &(TNEF->MapiProperties)) < 0) { printf("ERROR Parsing MAPI block\n"); return -1; }; if (TNEF->Debug >= 3) { MAPIPrint(&(TNEF->MapiProperties)); } return 0; } int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p) { int i, j; DWORD num; BYTE *d; MAPIProperty *mp; DWORD type; DWORD length; variableLength *vl; WORD temp_word; DWORD temp_dword; DDWORD temp_ddword; int count = -1; int offset; d = data; p->count = SwapDWord((BYTE*)data, 4); d += 4; p->properties = calloc(p->count, sizeof(MAPIProperty)); ALLOCCHECK(p->properties); mp = p->properties; for (i = 0; i < p->count; i++) { if (count == -1) { mp->id = SwapDWord((BYTE*)d, 4); d += 4; mp->custom = 0; mp->count = 1; mp->namedproperty = 0; length = -1; if (PROP_ID(mp->id) >= 0x8000) { // Read the GUID SIZECHECK(16); memcpy(&(mp->guid[0]), d, 16); d += 16; SIZECHECK(4); length = SwapDWord((BYTE*)d, 4); d += sizeof(DWORD); if (length > 0) { mp->namedproperty = length; mp->propnames = calloc(length, sizeof(variableLength)); ALLOCCHECK(mp->propnames); while (length > 0) { SIZECHECK(4); type = SwapDWord((BYTE*)d, 4); mp->propnames[length - 1].data = calloc(type, sizeof(BYTE)); ALLOCCHECK(mp->propnames[length - 1].data); mp->propnames[length - 1].size = type; d += 4; for (j = 0; j < (type >> 1); j++) { SIZECHECK(j*2); mp->propnames[length - 1].data[j] = d[j * 2]; } d += type + ((type % 4) ? (4 - type % 4) : 0); length--; } } else { // READ the type SIZECHECK(sizeof(DWORD)); type = SwapDWord((BYTE*)d, sizeof(DWORD)); d += sizeof(DWORD); mp->id = PROP_TAG(PROP_TYPE(mp->id), type); } mp->custom = 1; } DEBUG2(TNEF->Debug, 3, "Type id = %04x, Prop id = %04x", PROP_TYPE(mp->id), PROP_ID(mp->id)); if (PROP_TYPE(mp->id) & MV_FLAG) { mp->id = PROP_TAG(PROP_TYPE(mp->id) - MV_FLAG, PROP_ID(mp->id)); SIZECHECK(4); mp->count = SwapDWord((BYTE*)d, 4); d += 4; count = 0; } mp->data = calloc(mp->count, sizeof(variableLength)); ALLOCCHECK(mp->data); vl = mp->data; } else { i--; count++; vl = &(mp->data[count]); } switch (PROP_TYPE(mp->id)) { case PT_BINARY: case PT_OBJECT: case PT_STRING8: case PT_UNICODE: // First number of objects (assume 1 for now) if (count == -1) { SIZECHECK(4); vl->size = SwapDWord((BYTE*)d, 4); d += 4; } // now size of object SIZECHECK(4); vl->size = SwapDWord((BYTE*)d, 4); d += 4; // now actual object if (vl->size != 0) { SIZECHECK(vl->size); if (PROP_TYPE(mp->id) == PT_UNICODE) { vl->data =(BYTE*) to_utf8(vl->size, (char*)d); } else { vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); memcpy(vl->data, d, vl->size); } } else { vl->data = NULL; } // Make sure to read in a multiple of 4 num = vl->size; offset = ((num % 4) ? (4 - num % 4) : 0); d += num + ((num % 4) ? (4 - num % 4) : 0); break; case PT_I2: // Read in 2 bytes, but proceed by 4 bytes vl->size = 2; vl->data = calloc(vl->size, sizeof(WORD)); ALLOCCHECK(vl->data); SIZECHECK(sizeof(WORD)) temp_word = SwapWord((BYTE*)d, sizeof(WORD)); memcpy(vl->data, &temp_word, vl->size); d += 4; break; case PT_BOOLEAN: case PT_LONG: case PT_R4: case PT_CURRENCY: case PT_APPTIME: case PT_ERROR: vl->size = 4; vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); SIZECHECK(4); temp_dword = SwapDWord((BYTE*)d, 4); memcpy(vl->data, &temp_dword, vl->size); d += 4; break; case PT_DOUBLE: case PT_I8: case PT_SYSTIME: vl->size = 8; vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); SIZECHECK(8); temp_ddword = SwapDDWord(d, 8); memcpy(vl->data, &temp_ddword, vl->size); d += 8; break; case PT_CLSID: vl->size = 16; vl->data = calloc(vl->size, sizeof(BYTE)); ALLOCCHECK(vl->data); SIZECHECK(vl->size); memcpy(vl->data, d, vl->size); d+=16; break; default: printf("Bad file\n"); exit(-1); } switch (PROP_ID(mp->id)) { case PR_SUBJECT: case PR_SUBJECT_IPM: case PR_ORIGINAL_SUBJECT: case PR_NORMALIZED_SUBJECT: case PR_CONVERSATION_TOPIC: DEBUG(TNEF->Debug, 3, "Got a Subject"); if (TNEF->subject.size == 0) { int i; DEBUG(TNEF->Debug, 3, "Assigning a Subject"); TNEF->subject.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(TNEF->subject.data); TNEF->subject.size = vl->size; memcpy(TNEF->subject.data, vl->data, vl->size); // Unfortunately, we have to normalize out some invalid // characters, or else the file won't write for (i = 0; i != TNEF->subject.size; i++) { switch (TNEF->subject.data[i]) { case '\\': case '/': case '\0': TNEF->subject.data[i] = '_'; break; } } } break; } if (count == (mp->count - 1)) { count = -1; } if (count == -1) { mp++; } } if ((d - data) < size) { if (TNEF->Debug >= 1) { printf("ERROR DURING MAPI READ\n"); printf("Read %td bytes, Expected %u bytes\n", (d - data), size); printf("%td bytes missing\n", size - (d - data)); } } else if ((d - data) > size) { if (TNEF->Debug >= 1) { printf("ERROR DURING MAPI READ\n"); printf("Read %td bytes, Expected %u bytes\n", (d - data), size); printf("%li bytes extra\n", (d - data) - size); } } return 0; } // ----------------------------------------------------------------------------- int TNEFSentFor STD_ARGLIST { WORD name_length, addr_length; BYTE *d; d = (BYTE*)data; while ((d - (BYTE*)data) < size) { SIZECHECK(sizeof(WORD)); name_length = SwapWord((BYTE*)d, sizeof(WORD)); d += sizeof(WORD); if (TNEF->Debug >= 1) printf("Sent For : %s", d); d += name_length; SIZECHECK(sizeof(WORD)); addr_length = SwapWord((BYTE*)d, sizeof(WORD)); d += sizeof(WORD); if (TNEF->Debug >= 1) printf("<%s>\n", d); d += addr_length; } return 0; } // ----------------------------------------------------------------------------- int TNEFDateHandler STD_ARGLIST { dtr *Date; Attachment *p; WORD * tmp_src, *tmp_dst; int i; p = &(TNEF->starting_attach); switch (TNEFList[id].id) { case attDateSent: Date = &(TNEF->dateSent); break; case attDateRecd: Date = &(TNEF->dateReceived); break; case attDateModified: Date = &(TNEF->dateModified); break; case attDateStart: Date = &(TNEF->DateStart); break; case attDateEnd: Date = &(TNEF->DateEnd); break; case attAttachCreateDate: while (p->next != NULL) p = p->next; Date = &(p->CreateDate); break; case attAttachModifyDate: while (p->next != NULL) p = p->next; Date = &(p->ModifyDate); break; default: if (TNEF->Debug >= 1) printf("MISSING CASE\n"); return YTNEF_UNKNOWN_PROPERTY; } tmp_src = (WORD *)data; tmp_dst = (WORD *)Date; for (i = 0; i < sizeof(dtr) / sizeof(WORD); i++) { *tmp_dst++ = SwapWord((BYTE *)tmp_src++, sizeof(WORD)); } return 0; } void TNEFPrintDate(dtr Date) { char days[7][15] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; char months[12][15] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; if (Date.wDayOfWeek < 7) printf("%s ", days[Date.wDayOfWeek]); if ((Date.wMonth < 13) && (Date.wMonth > 0)) printf("%s ", months[Date.wMonth - 1]); printf("%hu, %hu ", Date.wDay, Date.wYear); if (Date.wHour > 12) printf("%i:%02hu:%02hu pm", (Date.wHour - 12), Date.wMinute, Date.wSecond); else if (Date.wHour == 12) printf("%hu:%02hu:%02hu pm", (Date.wHour), Date.wMinute, Date.wSecond); else printf("%hu:%02hu:%02hu am", Date.wHour, Date.wMinute, Date.wSecond); } // ----------------------------------------------------------------------------- int TNEFHexBreakdown STD_ARGLIST { int i; if (TNEF->Debug == 0) return 0; printf("%s: [%i bytes] \n", TNEFList[id].name, size); for (i = 0; i < size; i++) { printf("%02x ", data[i]); if ((i + 1) % 16 == 0) printf("\n"); } printf("\n"); return 0; } // ----------------------------------------------------------------------------- int TNEFDetailedPrint STD_ARGLIST { int i; if (TNEF->Debug == 0) return 0; printf("%s: [%i bytes] \n", TNEFList[id].name, size); for (i = 0; i < size; i++) { printf("%c", data[i]); } printf("\n"); return 0; } // ----------------------------------------------------------------------------- int TNEFAttachmentFilename STD_ARGLIST { Attachment *p; p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; p->Title.size = size; p->Title.data = calloc(size, sizeof(BYTE)); ALLOCCHECK(p->Title.data); memcpy(p->Title.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFAttachmentSave STD_ARGLIST { Attachment *p; p = &(TNEF->starting_attach); while (p->next != NULL) p = p->next; p->FileData.data = calloc(sizeof(char), size); ALLOCCHECK(p->FileData.data); p->FileData.size = size; memcpy(p->FileData.data, data, size); return 0; } // ----------------------------------------------------------------------------- int TNEFPriority STD_ARGLIST { DWORD value; value = SwapDWord((BYTE*)data, size); switch (value) { case 3: sprintf((TNEF->priority), "high"); break; case 2: sprintf((TNEF->priority), "normal"); break; case 1: sprintf((TNEF->priority), "low"); break; default: sprintf((TNEF->priority), "N/A"); break; } return 0; } // ----------------------------------------------------------------------------- int TNEFCheckForSignature(DWORD sig) { DWORD signature = 0x223E9F78; sig = SwapDWord((BYTE *)&sig, sizeof(DWORD)); if (signature == sig) { return 0; } else { return YTNEF_NOT_TNEF_STREAM; } } // ----------------------------------------------------------------------------- int TNEFGetKey(TNEFStruct *TNEF, WORD *key) { if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(WORD), 1, key) < 1) { if (TNEF->Debug >= 1) printf("Error reading Key\n"); return YTNEF_ERROR_READING_DATA; } *key = SwapWord((BYTE *)key, sizeof(WORD)); DEBUG1(TNEF->Debug, 2, "Key = 0x%X", *key); DEBUG1(TNEF->Debug, 2, "Key = %i", *key); return 0; } // ----------------------------------------------------------------------------- int TNEFGetHeader(TNEFStruct *TNEF, DWORD *type, DWORD *size) { BYTE component; DEBUG(TNEF->Debug, 2, "About to read Component"); if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(BYTE), 1, &component) < 1) { return YTNEF_ERROR_READING_DATA; } DEBUG(TNEF->Debug, 2, "About to read type"); if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, type) < 1) { if (TNEF->Debug >= 1) printf("ERROR: Error reading type\n"); return YTNEF_ERROR_READING_DATA; } DEBUG1(TNEF->Debug, 2, "Type = 0x%X", *type); DEBUG1(TNEF->Debug, 2, "Type = %u", *type); DEBUG(TNEF->Debug, 2, "About to read size"); if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, size) < 1) { if (TNEF->Debug >= 1) printf("ERROR: Error reading size\n"); return YTNEF_ERROR_READING_DATA; } DEBUG1(TNEF->Debug, 2, "Size = %u", *size); *type = SwapDWord((BYTE *)type, sizeof(DWORD)); *size = SwapDWord((BYTE *)size, sizeof(DWORD)); return 0; } // ----------------------------------------------------------------------------- int TNEFRawRead(TNEFStruct *TNEF, BYTE *data, DWORD size, WORD *checksum) { WORD temp; int i; if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(BYTE), size, data) < size) { if (TNEF->Debug >= 1) printf("ERROR: Error reading data\n"); return YTNEF_ERROR_READING_DATA; } if (checksum != NULL) { *checksum = 0; for (i = 0; i < size; i++) { temp = data[i]; *checksum = (*checksum + temp); } } return 0; } #define INITVARLENGTH(x) (x).data = NULL; (x).size = 0; #define INITDTR(x) (x).wYear=0; (x).wMonth=0; (x).wDay=0; \ (x).wHour=0; (x).wMinute=0; (x).wSecond=0; \ (x).wDayOfWeek=0; #define INITSTR(x) memset((x), 0, sizeof(x)); void TNEFInitMapi(MAPIProps *p) { p->count = 0; p->properties = NULL; } void TNEFInitAttachment(Attachment *p) { INITDTR(p->Date); INITVARLENGTH(p->Title); INITVARLENGTH(p->MetaFile); INITDTR(p->CreateDate); INITDTR(p->ModifyDate); INITVARLENGTH(p->TransportFilename); INITVARLENGTH(p->FileData); INITVARLENGTH(p->IconData); memset(&(p->RenderData), 0, sizeof(renddata)); TNEFInitMapi(&(p->MAPI)); p->next = NULL; } void TNEFInitialize(TNEFStruct *TNEF) { INITSTR(TNEF->version); INITVARLENGTH(TNEF->from); INITVARLENGTH(TNEF->subject); INITDTR(TNEF->dateSent); INITDTR(TNEF->dateReceived); INITSTR(TNEF->messageStatus); INITSTR(TNEF->messageClass); INITSTR(TNEF->messageID); INITSTR(TNEF->parentID); INITSTR(TNEF->conversationID); INITVARLENGTH(TNEF->body); INITSTR(TNEF->priority); TNEFInitAttachment(&(TNEF->starting_attach)); INITDTR(TNEF->dateModified); TNEFInitMapi(&(TNEF->MapiProperties)); INITVARLENGTH(TNEF->CodePage); INITVARLENGTH(TNEF->OriginalMessageClass); INITVARLENGTH(TNEF->Owner); INITVARLENGTH(TNEF->SentFor); INITVARLENGTH(TNEF->Delegate); INITDTR(TNEF->DateStart); INITDTR(TNEF->DateEnd); INITVARLENGTH(TNEF->AidOwner); TNEF->RequestRes = 0; TNEF->IO.data = NULL; TNEF->IO.InitProc = NULL; TNEF->IO.ReadProc = NULL; TNEF->IO.CloseProc = NULL; } #undef INITVARLENGTH #undef INITDTR #undef INITSTR #define FREEVARLENGTH(x) if ((x).size > 0) { \ free((x).data); (x).size =0; } void TNEFFree(TNEFStruct *TNEF) { Attachment *p, *store; FREEVARLENGTH(TNEF->from); FREEVARLENGTH(TNEF->subject); FREEVARLENGTH(TNEF->body); FREEVARLENGTH(TNEF->CodePage); FREEVARLENGTH(TNEF->OriginalMessageClass); FREEVARLENGTH(TNEF->Owner); FREEVARLENGTH(TNEF->SentFor); FREEVARLENGTH(TNEF->Delegate); FREEVARLENGTH(TNEF->AidOwner); TNEFFreeMapiProps(&(TNEF->MapiProperties)); p = TNEF->starting_attach.next; while (p != NULL) { TNEFFreeAttachment(p); store = p->next; free(p); p = store; } } void TNEFFreeAttachment(Attachment *p) { FREEVARLENGTH(p->Title); FREEVARLENGTH(p->MetaFile); FREEVARLENGTH(p->TransportFilename); FREEVARLENGTH(p->FileData); FREEVARLENGTH(p->IconData); TNEFFreeMapiProps(&(p->MAPI)); } void TNEFFreeMapiProps(MAPIProps *p) { int i, j; for (i = 0; i < p->count; i++) { for (j = 0; j < p->properties[i].count; j++) { FREEVARLENGTH(p->properties[i].data[j]); } free(p->properties[i].data); for (j = 0; j < p->properties[i].namedproperty; j++) { FREEVARLENGTH(p->properties[i].propnames[j]); } free(p->properties[i].propnames); } free(p->properties); p->count = 0; } #undef FREEVARLENGTH // Procedures to handle File IO int TNEFFile_Open(TNEFIOStruct *IO) { TNEFFileInfo *finfo; finfo = (TNEFFileInfo *)IO->data; DEBUG1(finfo->Debug, 3, "Opening %s", finfo->filename); if ((finfo->fptr = fopen(finfo->filename, "rb")) == NULL) { return -1; } else { return 0; } } int TNEFFile_Read(TNEFIOStruct *IO, int size, int count, void *dest) { TNEFFileInfo *finfo; finfo = (TNEFFileInfo *)IO->data; DEBUG2(finfo->Debug, 3, "Reading %i blocks of %i size", count, size); if (finfo->fptr != NULL) { return fread((BYTE *)dest, size, count, finfo->fptr); } else { return -1; } } int TNEFFile_Close(TNEFIOStruct *IO) { TNEFFileInfo *finfo; finfo = (TNEFFileInfo *)IO->data; DEBUG1(finfo->Debug, 3, "Closing file %s", finfo->filename); if (finfo->fptr != NULL) { fclose(finfo->fptr); finfo->fptr = NULL; } return 0; } int TNEFParseFile(char *filename, TNEFStruct *TNEF) { TNEFFileInfo finfo; if (TNEF->Debug >= 1) printf("Attempting to parse %s...\n", filename); finfo.filename = filename; finfo.fptr = NULL; finfo.Debug = TNEF->Debug; TNEF->IO.data = (void *)&finfo; TNEF->IO.InitProc = TNEFFile_Open; TNEF->IO.ReadProc = TNEFFile_Read; TNEF->IO.CloseProc = TNEFFile_Close; return TNEFParse(TNEF); } //------------------------------------------------------------- // Procedures to handle Memory IO int TNEFMemory_Open(TNEFIOStruct *IO) { TNEFMemInfo *minfo; minfo = (TNEFMemInfo *)IO->data; minfo->ptr = minfo->dataStart; return 0; } int TNEFMemory_Read(TNEFIOStruct *IO, int size, int count, void *dest) { TNEFMemInfo *minfo; int length; long max; minfo = (TNEFMemInfo *)IO->data; length = count * size; max = (minfo->dataStart + minfo->size) - (minfo->ptr); if (length > max) { return -1; } DEBUG1(minfo->Debug, 3, "Copying %i bytes", length); memcpy(dest, minfo->ptr, length); minfo->ptr += length; return count; } int TNEFMemory_Close(TNEFIOStruct *IO) { // Do nothing, really... return 0; } int TNEFParseMemory(BYTE *memory, long size, TNEFStruct *TNEF) { TNEFMemInfo minfo; DEBUG(TNEF->Debug, 1, "Attempting to parse memory block...\n"); minfo.dataStart = memory; minfo.ptr = memory; minfo.size = size; minfo.Debug = TNEF->Debug; TNEF->IO.data = (void *)&minfo; TNEF->IO.InitProc = TNEFMemory_Open; TNEF->IO.ReadProc = TNEFMemory_Read; TNEF->IO.CloseProc = TNEFMemory_Close; return TNEFParse(TNEF); } int TNEFParse(TNEFStruct *TNEF) { WORD key; DWORD type; DWORD size; DWORD signature; BYTE *data; WORD checksum, header_checksum; int i; if (TNEF->IO.ReadProc == NULL) { printf("ERROR: Setup incorrectly: No ReadProc\n"); return YTNEF_INCORRECT_SETUP; } if (TNEF->IO.InitProc != NULL) { DEBUG(TNEF->Debug, 2, "About to initialize"); if (TNEF->IO.InitProc(&TNEF->IO) != 0) { return YTNEF_CANNOT_INIT_DATA; } DEBUG(TNEF->Debug, 2, "Initialization finished"); } DEBUG(TNEF->Debug, 2, "Reading Signature"); if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) { printf("ERROR: Error reading signature\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_READING_DATA; } DEBUG(TNEF->Debug, 2, "Checking Signature"); if (TNEFCheckForSignature(signature) < 0) { printf("ERROR: Signature does not match. Not TNEF.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NOT_TNEF_STREAM; } DEBUG(TNEF->Debug, 2, "Reading Key."); if (TNEFGetKey(TNEF, &key) < 0) { printf("ERROR: Unable to retrieve key.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NO_KEY; } DEBUG(TNEF->Debug, 2, "Starting Full Processing."); while (TNEFGetHeader(TNEF, &type, &size) == 0) { DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size); DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size); if(size == 0) { printf("ERROR: Field with size of 0\n"); return YTNEF_ERROR_READING_DATA; } data = calloc(size, sizeof(BYTE)); ALLOCCHECK(data); if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) { printf("ERROR: Unable to read data.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) { printf("ERROR: Unable to read checksum.\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } checksum = SwapWord((BYTE *)&checksum, sizeof(WORD)); if (checksum != header_checksum) { printf("ERROR: Checksum mismatch. Data corruption?:\n"); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_BAD_CHECKSUM; } for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) { if (TNEFList[i].id == type) { if (TNEFList[i].handler != NULL) { if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) { free(data); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_IN_HANDLER; } else { // Found our handler and processed it. now time to get out break; } } else { DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes", TNEFList[i].name, size); } } } free(data); } if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return 0; } // ---------------------------------------------------------------------------- variableLength *MAPIFindUserProp(MAPIProps *p, unsigned int ID) { int i; if (p != NULL) { for (i = 0; i < p->count; i++) { if ((p->properties[i].id == ID) && (p->properties[i].custom == 1)) { return (p->properties[i].data); } } } return MAPI_UNDEFINED; } variableLength *MAPIFindProperty(MAPIProps *p, unsigned int ID) { int i; if (p != NULL) { for (i = 0; i < p->count; i++) { if ((p->properties[i].id == ID) && (p->properties[i].custom == 0)) { return (p->properties[i].data); } } } return MAPI_UNDEFINED; } int MAPISysTimetoDTR(BYTE *data, dtr *thedate) { DDWORD ddword_tmp; int startingdate = 0; int tmp_date; int days_in_year = 365; unsigned int months[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; ddword_tmp = *((DDWORD *)data); ddword_tmp = ddword_tmp / 10; // micro-s ddword_tmp /= 1000; // ms ddword_tmp /= 1000; // s thedate->wSecond = (ddword_tmp % 60); ddword_tmp /= 60; // seconds to minutes thedate->wMinute = (ddword_tmp % 60); ddword_tmp /= 60; //minutes to hours thedate->wHour = (ddword_tmp % 24); ddword_tmp /= 24; // Hours to days // Now calculate the year based on # of days thedate->wYear = 1601; startingdate = 1; while (ddword_tmp >= days_in_year) { ddword_tmp -= days_in_year; thedate->wYear++; days_in_year = 365; startingdate++; if ((thedate->wYear % 4) == 0) { if ((thedate->wYear % 100) == 0) { // if the year is 1700,1800,1900, etc, then it is only // a leap year if exactly divisible by 400, not 4. if ((thedate->wYear % 400) == 0) { startingdate++; days_in_year = 366; } } else { startingdate++; days_in_year = 366; } } startingdate %= 7; } // the remaining number is the day # in this year // So now calculate the Month, & Day of month if ((thedate->wYear % 4) == 0) { // 29 days in february in a leap year months[1] = 29; } tmp_date = (int)ddword_tmp; thedate->wDayOfWeek = (tmp_date + startingdate) % 7; thedate->wMonth = 0; while (tmp_date > months[thedate->wMonth]) { tmp_date -= months[thedate->wMonth]; thedate->wMonth++; } thedate->wMonth++; thedate->wDay = tmp_date + 1; return 0; } void MAPIPrint(MAPIProps *p) { int j, i, index, h, x; DDWORD *ddword_ptr; DDWORD ddword_tmp; dtr thedate; MAPIProperty *mapi; variableLength *mapidata; variableLength vlTemp; int found; for (j = 0; j < p->count; j++) { mapi = &(p->properties[j]); printf(" #%i: Type: [", j); switch (PROP_TYPE(mapi->id)) { case PT_UNSPECIFIED: printf(" NONE "); break; case PT_NULL: printf(" NULL "); break; case PT_I2: printf(" I2 "); break; case PT_LONG: printf(" LONG "); break; case PT_R4: printf(" R4 "); break; case PT_DOUBLE: printf(" DOUBLE "); break; case PT_CURRENCY: printf("CURRENCY "); break; case PT_APPTIME: printf("APP TIME "); break; case PT_ERROR: printf(" ERROR "); break; case PT_BOOLEAN: printf(" BOOLEAN "); break; case PT_OBJECT: printf(" OBJECT "); break; case PT_I8: printf(" I8 "); break; case PT_STRING8: printf(" STRING8 "); break; case PT_UNICODE: printf(" UNICODE "); break; case PT_SYSTIME: printf("SYS TIME "); break; case PT_CLSID: printf("OLE GUID "); break; case PT_BINARY: printf(" BINARY "); break; default: printf("<%x>", PROP_TYPE(mapi->id)); break; } printf("] Code: ["); if (mapi->custom == 1) { printf("UD:x%04x", PROP_ID(mapi->id)); } else { found = 0; for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) { if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) { printf("%s", MPList[index].name); found = 1; } } if (found == 0) { printf("0x%04x", PROP_ID(mapi->id)); } } printf("]\n"); if (mapi->namedproperty > 0) { for (i = 0; i < mapi->namedproperty; i++) { printf(" Name: %s\n", mapi->propnames[i].data); } } for (i = 0; i < mapi->count; i++) { mapidata = &(mapi->data[i]); if (mapi->count > 1) { printf(" [%i/%u] ", i, mapi->count); } else { printf(" "); } printf("Size: %i", mapidata->size); switch (PROP_TYPE(mapi->id)) { case PT_SYSTIME: MAPISysTimetoDTR(mapidata->data, &thedate); printf(" Value: "); ddword_tmp = *((DDWORD *)mapidata->data); TNEFPrintDate(thedate); printf(" [HEX: "); for (x = 0; x < sizeof(ddword_tmp); x++) { printf(" %02x", (BYTE)mapidata->data[x]); } printf("] (%llu)\n", ddword_tmp); break; case PT_LONG: printf(" Value: %i\n", *((int*)mapidata->data)); break; case PT_I2: printf(" Value: %hi\n", *((short int*)mapidata->data)); break; case PT_BOOLEAN: if (mapi->data->data[0] != 0) { printf(" Value: True\n"); } else { printf(" Value: False\n"); } break; case PT_OBJECT: printf("\n"); break; case PT_BINARY: if (IsCompressedRTF(mapidata) == 1) { printf(" Detected Compressed RTF. "); printf("Decompressed text follows\n"); printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) { printf("%s\n", vlTemp.data); free(vlTemp.data); } printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"); } else { printf(" Value: ["); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf("%c", mapidata->data[h]); } else { printf("."); } } printf("]\n"); } break; case PT_STRING8: printf(" Value: [%s]\n", mapidata->data); if (strlen((char*)mapidata->data) != mapidata->size - 1) { printf("Detected Hidden data: ["); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf("%c", mapidata->data[h]); } else { printf("."); } } printf("]\n"); } break; case PT_CLSID: printf(" Value: "); printf("[HEX: "); for(x=0; x< 16; x++) { printf(" %02x", (BYTE)mapidata->data[x]); } printf("]\n"); break; default: printf(" Value: [%s]\n", mapidata->data); } } } } int IsCompressedRTF(variableLength *p) { unsigned int in; BYTE *src; ULONG magic; if (p->size < 4) return 0; src = p->data; in = 0; in += 4; in += 4; magic = SwapDWord((BYTE*)src + in, 4); if (magic == 0x414c454d) { return 1; } else if (magic == 0x75465a4c) { return 1; } else { return 0; } } BYTE *DecompressRTF(variableLength *p, int *size) { BYTE *dst; // destination for uncompressed bytes BYTE *src; unsigned int in; unsigned int out; variableLength comp_Prebuf; ULONG compressedSize, uncompressedSize, magic; comp_Prebuf.size = strlen(RTF_PREBUF); comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1); ALLOCCHECK_CHAR(comp_Prebuf.data); memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size); src = p->data; in = 0; if (p->size < 20) { printf("File too small\n"); return(NULL); } compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; magic = SwapDWord((BYTE*)src + in, 4); in += 4; in += 4; // check size excluding the size field itself if (compressedSize != p->size - 4) { printf(" Size Mismatch: %u != %i\n", compressedSize, p->size - 4); free(comp_Prebuf.data); return NULL; } // process the data if (magic == 0x414c454d) { // magic number that identifies the stream as a uncompressed stream dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + 4, uncompressedSize); } else if (magic == 0x75465a4c) { // magic number that identifies the stream as a compressed stream int flagCount = 0; int flags = 0; // Prevent overflow on 32 Bit Systems if (comp_Prebuf.size >= INT_MAX - uncompressedSize) { printf("Corrupted file\n"); exit(-1); } dst = calloc(comp_Prebuf.size + uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, comp_Prebuf.data, comp_Prebuf.size); out = comp_Prebuf.size; while ((out < (comp_Prebuf.size + uncompressedSize)) && (in < p->size)) { // each flag byte flags 8 literals/references, 1 per bit flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1; if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal unsigned int offset = src[in++]; unsigned int length = src[in++]; unsigned int end; offset = (offset << 4) | (length >> 4); // the offset relative to block start length = (length & 0xF) + 2; // the number of bytes to copy // the decompression buffer is supposed to wrap around back // to the beginning when the end is reached. we save the // need for such a buffer by pointing straight into the data // buffer, and simulating this behaviour by modifying the // pointers appropriately. offset = (out / 4096) * 4096 + offset; if (offset >= out) // take from previous block offset -= 4096; // note: can't use System.arraycopy, because the referenced // bytes can cross through the current out position. end = offset + length; while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize)) && (offset < (comp_Prebuf.size + uncompressedSize))) dst[out++] = dst[offset++]; } else { // literal if ((out >= (comp_Prebuf.size + uncompressedSize)) || (in >= p->size)) { printf("Corrupted stream\n"); exit(-1); } dst[out++] = src[in++]; } } // copy it back without the prebuffered data src = dst; dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + comp_Prebuf.size, uncompressedSize); free(src); *size = uncompressedSize; free(comp_Prebuf.data); return dst; } else { // unknown magic number printf("Unknown compression type (magic number %x)\n", magic); } free(comp_Prebuf.data); return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3209_1
crossvul-cpp_data_good_2727_0
/* * Copyright (c) 1998-2007 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource ReSerVation Protocol (RSVP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ethertype.h" #include "gmpls.h" #include "af.h" #include "signature.h" static const char tstr[] = " [|rsvp]"; /* * RFC 2205 common header * * 0 1 2 3 * +-------------+-------------+-------------+-------------+ * | Vers | Flags| Msg Type | RSVP Checksum | * +-------------+-------------+-------------+-------------+ * | Send_TTL | (Reserved) | RSVP Length | * +-------------+-------------+-------------+-------------+ * */ struct rsvp_common_header { uint8_t version_flags; uint8_t msg_type; uint8_t checksum[2]; uint8_t ttl; uint8_t reserved; uint8_t length[2]; }; /* * RFC2205 object header * * * 0 1 2 3 * +-------------+-------------+-------------+-------------+ * | Length (bytes) | Class-Num | C-Type | * +-------------+-------------+-------------+-------------+ * | | * // (Object contents) // * | | * +-------------+-------------+-------------+-------------+ */ struct rsvp_object_header { uint8_t length[2]; uint8_t class_num; uint8_t ctype; }; #define RSVP_VERSION 1 #define RSVP_EXTRACT_VERSION(x) (((x)&0xf0)>>4) #define RSVP_EXTRACT_FLAGS(x) ((x)&0x0f) #define RSVP_MSGTYPE_PATH 1 #define RSVP_MSGTYPE_RESV 2 #define RSVP_MSGTYPE_PATHERR 3 #define RSVP_MSGTYPE_RESVERR 4 #define RSVP_MSGTYPE_PATHTEAR 5 #define RSVP_MSGTYPE_RESVTEAR 6 #define RSVP_MSGTYPE_RESVCONF 7 #define RSVP_MSGTYPE_BUNDLE 12 #define RSVP_MSGTYPE_ACK 13 #define RSVP_MSGTYPE_HELLO_OLD 14 /* ancient Hellos */ #define RSVP_MSGTYPE_SREFRESH 15 #define RSVP_MSGTYPE_HELLO 20 static const struct tok rsvp_msg_type_values[] = { { RSVP_MSGTYPE_PATH, "Path" }, { RSVP_MSGTYPE_RESV, "Resv" }, { RSVP_MSGTYPE_PATHERR, "PathErr" }, { RSVP_MSGTYPE_RESVERR, "ResvErr" }, { RSVP_MSGTYPE_PATHTEAR, "PathTear" }, { RSVP_MSGTYPE_RESVTEAR, "ResvTear" }, { RSVP_MSGTYPE_RESVCONF, "ResvConf" }, { RSVP_MSGTYPE_BUNDLE, "Bundle" }, { RSVP_MSGTYPE_ACK, "Acknowledgement" }, { RSVP_MSGTYPE_HELLO_OLD, "Hello (Old)" }, { RSVP_MSGTYPE_SREFRESH, "Refresh" }, { RSVP_MSGTYPE_HELLO, "Hello" }, { 0, NULL} }; static const struct tok rsvp_header_flag_values[] = { { 0x01, "Refresh reduction capable" }, /* rfc2961 */ { 0, NULL} }; #define RSVP_OBJ_SESSION 1 /* rfc2205 */ #define RSVP_OBJ_RSVP_HOP 3 /* rfc2205, rfc3473 */ #define RSVP_OBJ_INTEGRITY 4 /* rfc2747 */ #define RSVP_OBJ_TIME_VALUES 5 /* rfc2205 */ #define RSVP_OBJ_ERROR_SPEC 6 #define RSVP_OBJ_SCOPE 7 #define RSVP_OBJ_STYLE 8 /* rfc2205 */ #define RSVP_OBJ_FLOWSPEC 9 /* rfc2215 */ #define RSVP_OBJ_FILTERSPEC 10 /* rfc2215 */ #define RSVP_OBJ_SENDER_TEMPLATE 11 #define RSVP_OBJ_SENDER_TSPEC 12 /* rfc2215 */ #define RSVP_OBJ_ADSPEC 13 /* rfc2215 */ #define RSVP_OBJ_POLICY_DATA 14 #define RSVP_OBJ_CONFIRM 15 /* rfc2205 */ #define RSVP_OBJ_LABEL 16 /* rfc3209 */ #define RSVP_OBJ_LABEL_REQ 19 /* rfc3209 */ #define RSVP_OBJ_ERO 20 /* rfc3209 */ #define RSVP_OBJ_RRO 21 /* rfc3209 */ #define RSVP_OBJ_HELLO 22 /* rfc3209 */ #define RSVP_OBJ_MESSAGE_ID 23 /* rfc2961 */ #define RSVP_OBJ_MESSAGE_ID_ACK 24 /* rfc2961 */ #define RSVP_OBJ_MESSAGE_ID_LIST 25 /* rfc2961 */ #define RSVP_OBJ_RECOVERY_LABEL 34 /* rfc3473 */ #define RSVP_OBJ_UPSTREAM_LABEL 35 /* rfc3473 */ #define RSVP_OBJ_LABEL_SET 36 /* rfc3473 */ #define RSVP_OBJ_PROTECTION 37 /* rfc3473 */ #define RSVP_OBJ_S2L 50 /* rfc4875 */ #define RSVP_OBJ_DETOUR 63 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */ #define RSVP_OBJ_CLASSTYPE 66 /* rfc4124 */ #define RSVP_OBJ_CLASSTYPE_OLD 125 /* draft-ietf-tewg-diff-te-proto-07 */ #define RSVP_OBJ_SUGGESTED_LABEL 129 /* rfc3473 */ #define RSVP_OBJ_ACCEPT_LABEL_SET 130 /* rfc3473 */ #define RSVP_OBJ_RESTART_CAPABILITY 131 /* rfc3473 */ #define RSVP_OBJ_NOTIFY_REQ 195 /* rfc3473 */ #define RSVP_OBJ_ADMIN_STATUS 196 /* rfc3473 */ #define RSVP_OBJ_PROPERTIES 204 /* juniper proprietary */ #define RSVP_OBJ_FASTREROUTE 205 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */ #define RSVP_OBJ_SESSION_ATTRIBUTE 207 /* rfc3209 */ #define RSVP_OBJ_GENERALIZED_UNI 229 /* OIF RSVP extensions UNI 1.0 Signaling, Rel. 2 */ #define RSVP_OBJ_CALL_ID 230 /* rfc3474 */ #define RSVP_OBJ_CALL_OPS 236 /* rfc3474 */ static const struct tok rsvp_obj_values[] = { { RSVP_OBJ_SESSION, "Session" }, { RSVP_OBJ_RSVP_HOP, "RSVP Hop" }, { RSVP_OBJ_INTEGRITY, "Integrity" }, { RSVP_OBJ_TIME_VALUES, "Time Values" }, { RSVP_OBJ_ERROR_SPEC, "Error Spec" }, { RSVP_OBJ_SCOPE, "Scope" }, { RSVP_OBJ_STYLE, "Style" }, { RSVP_OBJ_FLOWSPEC, "Flowspec" }, { RSVP_OBJ_FILTERSPEC, "FilterSpec" }, { RSVP_OBJ_SENDER_TEMPLATE, "Sender Template" }, { RSVP_OBJ_SENDER_TSPEC, "Sender TSpec" }, { RSVP_OBJ_ADSPEC, "Adspec" }, { RSVP_OBJ_POLICY_DATA, "Policy Data" }, { RSVP_OBJ_CONFIRM, "Confirm" }, { RSVP_OBJ_LABEL, "Label" }, { RSVP_OBJ_LABEL_REQ, "Label Request" }, { RSVP_OBJ_ERO, "ERO" }, { RSVP_OBJ_RRO, "RRO" }, { RSVP_OBJ_HELLO, "Hello" }, { RSVP_OBJ_MESSAGE_ID, "Message ID" }, { RSVP_OBJ_MESSAGE_ID_ACK, "Message ID Ack" }, { RSVP_OBJ_MESSAGE_ID_LIST, "Message ID List" }, { RSVP_OBJ_RECOVERY_LABEL, "Recovery Label" }, { RSVP_OBJ_UPSTREAM_LABEL, "Upstream Label" }, { RSVP_OBJ_LABEL_SET, "Label Set" }, { RSVP_OBJ_ACCEPT_LABEL_SET, "Acceptable Label Set" }, { RSVP_OBJ_DETOUR, "Detour" }, { RSVP_OBJ_CLASSTYPE, "Class Type" }, { RSVP_OBJ_CLASSTYPE_OLD, "Class Type (old)" }, { RSVP_OBJ_SUGGESTED_LABEL, "Suggested Label" }, { RSVP_OBJ_PROPERTIES, "Properties" }, { RSVP_OBJ_FASTREROUTE, "Fast Re-Route" }, { RSVP_OBJ_SESSION_ATTRIBUTE, "Session Attribute" }, { RSVP_OBJ_GENERALIZED_UNI, "Generalized UNI" }, { RSVP_OBJ_CALL_ID, "Call-ID" }, { RSVP_OBJ_CALL_OPS, "Call Capability" }, { RSVP_OBJ_RESTART_CAPABILITY, "Restart Capability" }, { RSVP_OBJ_NOTIFY_REQ, "Notify Request" }, { RSVP_OBJ_PROTECTION, "Protection" }, { RSVP_OBJ_ADMIN_STATUS, "Administrative Status" }, { RSVP_OBJ_S2L, "Sub-LSP to LSP" }, { 0, NULL} }; #define RSVP_CTYPE_IPV4 1 #define RSVP_CTYPE_IPV6 2 #define RSVP_CTYPE_TUNNEL_IPV4 7 #define RSVP_CTYPE_TUNNEL_IPV6 8 #define RSVP_CTYPE_UNI_IPV4 11 /* OIF RSVP extensions UNI 1.0 Signaling Rel. 2 */ #define RSVP_CTYPE_1 1 #define RSVP_CTYPE_2 2 #define RSVP_CTYPE_3 3 #define RSVP_CTYPE_4 4 #define RSVP_CTYPE_12 12 #define RSVP_CTYPE_13 13 #define RSVP_CTYPE_14 14 /* * the ctypes are not globally unique so for * translating it to strings we build a table based * on objects offsetted by the ctype */ static const struct tok rsvp_ctype_values[] = { { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" }, { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" }, { 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_TIME_VALUES+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_1, "obsolete" }, { 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_2, "IntServ" }, { 256*RSVP_OBJ_SENDER_TSPEC+RSVP_CTYPE_2, "IntServ" }, { 256*RSVP_OBJ_ADSPEC+RSVP_CTYPE_2, "IntServ" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_3, "IPv6 Flow-label" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_UNI_IPV4, "UNI IPv4" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_13, "IPv4 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_14, "IPv6 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_MESSAGE_ID+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_1, "Message id ack" }, { 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_2, "Message id nack" }, { 256*RSVP_OBJ_MESSAGE_ID_LIST+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_STYLE+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_HELLO+RSVP_CTYPE_1, "Hello Request" }, { 256*RSVP_OBJ_HELLO+RSVP_CTYPE_2, "Hello Ack" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_1, "without label range" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_2, "with ATM label range" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_3, "with FR label range" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_4, "Generalized Label" }, { 256*RSVP_OBJ_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_ERO+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_RRO+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" }, { 256*RSVP_OBJ_RESTART_CAPABILITY+RSVP_CTYPE_1, "IPv4" }, { 256*RSVP_OBJ_SESSION_ATTRIBUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, /* old style*/ { 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_1, "1" }, /* new style */ { 256*RSVP_OBJ_DETOUR+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_PROPERTIES+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_ADMIN_STATUS+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_CLASSTYPE+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_CLASSTYPE_OLD+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_LABEL_SET+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_GENERALIZED_UNI+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV4, "IPv4 sub-LSP" }, { 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV6, "IPv6 sub-LSP" }, { 0, NULL} }; struct rsvp_obj_integrity_t { uint8_t flags; uint8_t res; uint8_t key_id[6]; uint8_t sequence[8]; uint8_t digest[16]; }; static const struct tok rsvp_obj_integrity_flag_values[] = { { 0x80, "Handshake" }, { 0, NULL} }; struct rsvp_obj_frr_t { uint8_t setup_prio; uint8_t hold_prio; uint8_t hop_limit; uint8_t flags; uint8_t bandwidth[4]; uint8_t include_any[4]; uint8_t exclude_any[4]; uint8_t include_all[4]; }; #define RSVP_OBJ_XRO_MASK_SUBOBJ(x) ((x)&0x7f) #define RSVP_OBJ_XRO_MASK_LOOSE(x) ((x)&0x80) #define RSVP_OBJ_XRO_RES 0 #define RSVP_OBJ_XRO_IPV4 1 #define RSVP_OBJ_XRO_IPV6 2 #define RSVP_OBJ_XRO_LABEL 3 #define RSVP_OBJ_XRO_ASN 32 #define RSVP_OBJ_XRO_MPLS 64 static const struct tok rsvp_obj_xro_values[] = { { RSVP_OBJ_XRO_RES, "Reserved" }, { RSVP_OBJ_XRO_IPV4, "IPv4 prefix" }, { RSVP_OBJ_XRO_IPV6, "IPv6 prefix" }, { RSVP_OBJ_XRO_LABEL, "Label" }, { RSVP_OBJ_XRO_ASN, "Autonomous system number" }, { RSVP_OBJ_XRO_MPLS, "MPLS label switched path termination" }, { 0, NULL} }; /* draft-ietf-mpls-rsvp-lsp-fastreroute-07.txt */ static const struct tok rsvp_obj_rro_flag_values[] = { { 0x01, "Local protection available" }, { 0x02, "Local protection in use" }, { 0x04, "Bandwidth protection" }, { 0x08, "Node protection" }, { 0, NULL} }; /* RFC3209 */ static const struct tok rsvp_obj_rro_label_flag_values[] = { { 0x01, "Global" }, { 0, NULL} }; static const struct tok rsvp_resstyle_values[] = { { 17, "Wildcard Filter" }, { 10, "Fixed Filter" }, { 18, "Shared Explicit" }, { 0, NULL} }; #define RSVP_OBJ_INTSERV_GUARANTEED_SERV 2 #define RSVP_OBJ_INTSERV_CONTROLLED_LOAD 5 static const struct tok rsvp_intserv_service_type_values[] = { { 1, "Default/Global Information" }, { RSVP_OBJ_INTSERV_GUARANTEED_SERV, "Guaranteed Service" }, { RSVP_OBJ_INTSERV_CONTROLLED_LOAD, "Controlled Load" }, { 0, NULL} }; static const struct tok rsvp_intserv_parameter_id_values[] = { { 4, "IS hop cnt" }, { 6, "Path b/w estimate" }, { 8, "Minimum path latency" }, { 10, "Composed MTU" }, { 127, "Token Bucket TSpec" }, { 130, "Guaranteed Service RSpec" }, { 133, "End-to-end composed value for C" }, { 134, "End-to-end composed value for D" }, { 135, "Since-last-reshaping point composed C" }, { 136, "Since-last-reshaping point composed D" }, { 0, NULL} }; static const struct tok rsvp_session_attribute_flag_values[] = { { 0x01, "Local Protection" }, { 0x02, "Label Recording" }, { 0x04, "SE Style" }, { 0x08, "Bandwidth protection" }, /* RFC4090 */ { 0x10, "Node protection" }, /* RFC4090 */ { 0, NULL} }; static const struct tok rsvp_obj_prop_tlv_values[] = { { 0x01, "Cos" }, { 0x02, "Metric 1" }, { 0x04, "Metric 2" }, { 0x08, "CCC Status" }, { 0x10, "Path Type" }, { 0, NULL} }; #define RSVP_OBJ_ERROR_SPEC_CODE_ROUTING 24 #define RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY 25 #define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE 28 #define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD 125 static const struct tok rsvp_obj_error_code_values[] = { { RSVP_OBJ_ERROR_SPEC_CODE_ROUTING, "Routing Problem" }, { RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY, "Notify Error" }, { RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE, "Diffserv TE Error" }, { RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD, "Diffserv TE Error (Old)" }, { 0, NULL} }; static const struct tok rsvp_obj_error_code_routing_values[] = { { 1, "Bad EXPLICIT_ROUTE object" }, { 2, "Bad strict node" }, { 3, "Bad loose node" }, { 4, "Bad initial subobject" }, { 5, "No route available toward destination" }, { 6, "Unacceptable label value" }, { 7, "RRO indicated routing loops" }, { 8, "non-RSVP-capable router in the path" }, { 9, "MPLS label allocation failure" }, { 10, "Unsupported L3PID" }, { 0, NULL} }; static const struct tok rsvp_obj_error_code_diffserv_te_values[] = { { 1, "Unexpected CT object" }, { 2, "Unsupported CT" }, { 3, "Invalid CT value" }, { 4, "CT/setup priority do not form a configured TE-Class" }, { 5, "CT/holding priority do not form a configured TE-Class" }, { 6, "CT/setup priority and CT/holding priority do not form a configured TE-Class" }, { 7, "Inconsistency between signaled PSC and signaled CT" }, { 8, "Inconsistency between signaled PHBs and signaled CT" }, { 0, NULL} }; /* rfc3473 / rfc 3471 */ static const struct tok rsvp_obj_admin_status_flag_values[] = { { 0x80000000, "Reflect" }, { 0x00000004, "Testing" }, { 0x00000002, "Admin-down" }, { 0x00000001, "Delete-in-progress" }, { 0, NULL} }; /* label set actions - rfc3471 */ #define LABEL_SET_INCLUSIVE_LIST 0 #define LABEL_SET_EXCLUSIVE_LIST 1 #define LABEL_SET_INCLUSIVE_RANGE 2 #define LABEL_SET_EXCLUSIVE_RANGE 3 static const struct tok rsvp_obj_label_set_action_values[] = { { LABEL_SET_INCLUSIVE_LIST, "Inclusive list" }, { LABEL_SET_EXCLUSIVE_LIST, "Exclusive list" }, { LABEL_SET_INCLUSIVE_RANGE, "Inclusive range" }, { LABEL_SET_EXCLUSIVE_RANGE, "Exclusive range" }, { 0, NULL} }; /* OIF RSVP extensions UNI 1.0 Signaling, release 2 */ #define RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS 1 #define RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS 2 #define RSVP_GEN_UNI_SUBOBJ_DIVERSITY 3 #define RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL 4 #define RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL 5 static const struct tok rsvp_obj_generalized_uni_values[] = { { RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS, "Source TNA address" }, { RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS, "Destination TNA address" }, { RSVP_GEN_UNI_SUBOBJ_DIVERSITY, "Diversity" }, { RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL, "Egress label" }, { RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL, "Service level" }, { 0, NULL} }; /* * this is a dissector for all the intserv defined * specs as defined per rfc2215 * it is called from various rsvp objects; * returns the amount of bytes being processed */ static int rsvp_intserv_print(netdissect_options *ndo, const u_char *tptr, u_short obj_tlen) { int parameter_id,parameter_length; union { float f; uint32_t i; } bw; if (obj_tlen < 4) return 0; parameter_id = *(tptr); ND_TCHECK2(*(tptr + 2), 2); parameter_length = EXTRACT_16BITS(tptr+2)<<2; /* convert wordcount to bytecount */ ND_PRINT((ndo, "\n\t Parameter ID: %s (%u), length: %u, Flags: [0x%02x]", tok2str(rsvp_intserv_parameter_id_values,"unknown",parameter_id), parameter_id, parameter_length, *(tptr + 1))); if (obj_tlen < parameter_length+4) return 0; switch(parameter_id) { /* parameter_id */ case 4: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 4 (e) | (f) | 1 (g) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IS hop cnt (32-bit unsigned integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tIS hop count: %u", EXTRACT_32BITS(tptr + 4))); } break; case 6: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6 (h) | (i) | 1 (j) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Path b/w estimate (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); bw.i = EXTRACT_32BITS(tptr+4); ND_PRINT((ndo, "\n\t\tPath b/w estimate: %.10g Mbps", bw.f / 125000)); } break; case 8: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 8 (k) | (l) | 1 (m) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Minimum path latency (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tMinimum path latency: ")); if (EXTRACT_32BITS(tptr+4) == 0xffffffff) ND_PRINT((ndo, "don't care")); else ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr + 4))); } break; case 10: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 10 (n) | (o) | 1 (p) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Composed MTU (32-bit unsigned integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tComposed MTU: %u bytes", EXTRACT_32BITS(tptr + 4))); } break; case 127: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 127 (e) | 0 (f) | 5 (g) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Token Bucket Rate [r] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Token Bucket Size [b] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Peak Data Rate [p] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Minimum Policed Unit [m] (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Maximum Packet Size [M] (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 20) { ND_TCHECK2(*(tptr + 4), 20); bw.i = EXTRACT_32BITS(tptr+4); ND_PRINT((ndo, "\n\t\tToken Bucket Rate: %.10g Mbps", bw.f / 125000)); bw.i = EXTRACT_32BITS(tptr+8); ND_PRINT((ndo, "\n\t\tToken Bucket Size: %.10g bytes", bw.f)); bw.i = EXTRACT_32BITS(tptr+12); ND_PRINT((ndo, "\n\t\tPeak Data Rate: %.10g Mbps", bw.f / 125000)); ND_PRINT((ndo, "\n\t\tMinimum Policed Unit: %u bytes", EXTRACT_32BITS(tptr + 16))); ND_PRINT((ndo, "\n\t\tMaximum Packet Size: %u bytes", EXTRACT_32BITS(tptr + 20))); } break; case 130: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 130 (h) | 0 (i) | 2 (j) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Rate [R] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Slack Term [S] (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 8) { ND_TCHECK2(*(tptr + 4), 8); bw.i = EXTRACT_32BITS(tptr+4); ND_PRINT((ndo, "\n\t\tRate: %.10g Mbps", bw.f / 125000)); ND_PRINT((ndo, "\n\t\tSlack Term: %u", EXTRACT_32BITS(tptr + 8))); } break; case 133: case 134: case 135: case 136: if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tValue: %u", EXTRACT_32BITS(tptr + 4))); } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr + 4, "\n\t\t", parameter_length); } return (parameter_length+4); /* header length 4 bytes */ trunc: ND_PRINT((ndo, "%s", tstr)); return 0; } /* * Clear checksum prior to signature verification. */ static void rsvp_clear_checksum(void *header) { struct rsvp_common_header *rsvp_com_header = (struct rsvp_common_header *) header; rsvp_com_header->checksum[0] = 0; rsvp_com_header->checksum[1] = 0; } static int rsvp_obj_print(netdissect_options *ndo, const u_char *pptr, u_int plen, const u_char *tptr, const char *ident, u_int tlen, const struct rsvp_common_header *rsvp_com_header) { const struct rsvp_object_header *rsvp_obj_header; const u_char *obj_tptr; union { const struct rsvp_obj_integrity_t *rsvp_obj_integrity; const struct rsvp_obj_frr_t *rsvp_obj_frr; } obj_ptr; u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; union { float f; uint32_t i; } bw; uint8_t namelen; u_int action, subchannel; while(tlen>=sizeof(struct rsvp_object_header)) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); rsvp_obj_header = (const struct rsvp_object_header *)tptr; rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); rsvp_obj_ctype=rsvp_obj_header->ctype; if(rsvp_obj_len % 4) { ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len)); return -1; } if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len, (unsigned long)sizeof(const struct rsvp_object_header))); return -1; } ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s", ident, tok2str(rsvp_obj_values, "Unknown", rsvp_obj_header->class_num), rsvp_obj_header->class_num, ((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject")); if (rsvp_obj_header->class_num > 128) ND_PRINT((ndo, " %s", ((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently")); ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u", tok2str(rsvp_ctype_values, "Unknown", ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), rsvp_obj_ctype, rsvp_obj_len)); if(tlen < rsvp_obj_len) { ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident)); return -1; } obj_tptr=tptr+sizeof(struct rsvp_object_header); obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); /* did we capture enough for fully decoding the object ? */ if (!ND_TTEST2(*tptr, rsvp_obj_len)) return -1; hexdump=FALSE; switch(rsvp_obj_header->class_num) { case RSVP_OBJ_SESSION: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return -1; ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+5), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return -1; ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in6_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+sizeof(struct in6_addr)+1), EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 36) return -1; ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ip6addr_string(ndo, obj_tptr + 20))); obj_tlen-=36; obj_tptr+=36; break; case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ if (obj_tlen < 26) return -1; ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+6), ip6addr_string(ndo, obj_tptr + 8))); obj_tlen-=26; obj_tptr+=26; break; case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_TUNNEL_IPV4: case RSVP_CTYPE_UNI_IPV4: if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_CONFIRM: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Receiver Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return -1; ND_PRINT((ndo, "%s IPv6 Receiver Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_NOTIFY_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return-1; ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ case RSVP_OBJ_LABEL: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Generalized Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u", ident, EXTRACT_32BITS(obj_tptr), ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_STYLE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]", ident, tok2str(rsvp_resstyle_values, "Unknown", EXTRACT_24BITS(obj_tptr+1)), *(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SENDER_TEMPLATE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" )); ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+4))&0xfff, (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+8))&0xfff, (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI", ident, (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "", (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : "")); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)", ident, tok2str(gmpls_encoding_values, "Unknown", *obj_tptr), *obj_tptr)); ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)", ident, tok2str(gmpls_switch_cap_values, "Unknown", *(obj_tptr+1)), *(obj_tptr+1), tok2str(gmpls_payload_values, "Unknown", EXTRACT_16BITS(obj_tptr+2)), EXTRACT_16BITS(obj_tptr + 2))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RRO: case RSVP_OBJ_ERO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: while(obj_tlen >= 4 ) { u_char length; ND_TCHECK2(*obj_tptr, 4); length = *(obj_tptr + 1); ND_PRINT((ndo, "%s Subobject Type: %s, length %u", ident, tok2str(rsvp_obj_xro_values, "Unknown %u", RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), length)); if (length == 0) { /* prevent infinite loops */ ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident)); break; } switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { u_char prefix_length; case RSVP_OBJ_XRO_IPV4: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); prefix_length = *(obj_tptr+6); if (prefix_length != 32) { ND_PRINT((ndo, " ERROR: Prefix length %u != 32", prefix_length)); goto invalid; } ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]", RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict", ipaddr_string(ndo, obj_tptr+2), *(obj_tptr+6), bittok2str(rsvp_obj_rro_flag_values, "none", *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ break; case RSVP_OBJ_XRO_LABEL: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u", bittok2str(rsvp_obj_rro_label_flag_values, "none", *(obj_tptr+2)), *(obj_tptr+2), tok2str(rsvp_ctype_values, "Unknown", *(obj_tptr+3) + 256*RSVP_OBJ_RRO), *(obj_tptr+3), EXTRACT_32BITS(obj_tptr + 4))); } obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_HELLO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RESTART_CAPABILITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SESSION_ATTRIBUTE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 4) return-1; namelen = *(obj_tptr+3); if (obj_tlen < 4+namelen) return-1; ND_PRINT((ndo, "%s Session Name: ", ident)); for (i = 0; i < namelen; i++) safeputchar(ndo, *(obj_tptr + 4 + i)); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)", ident, (int)*obj_tptr, (int)*(obj_tptr+1), bittok2str(rsvp_session_attribute_flag_values, "none", *(obj_tptr+2)), *(obj_tptr + 2))); obj_tlen-=4+*(obj_tptr+3); obj_tptr+=4+*(obj_tptr+3); break; default: hexdump=TRUE; } break; case RSVP_OBJ_GENERALIZED_UNI: switch(rsvp_obj_ctype) { int subobj_type,af,subobj_len,total_subobj_len; case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; /* read variable length subobjects */ total_subobj_len = obj_tlen; while(total_subobj_len > 0) { /* If RFC 3476 Section 3.1 defined that a sub-object of the * GENERALIZED_UNI RSVP object must have the Length field as * a multiple of 4, instead of the check below it would be * better to test total_subobj_len only once before the loop. * So long as it does not define it and this while loop does * not implement such a requirement, let's accept that within * each iteration subobj_len may happen to be a multiple of 1 * and test it and total_subobj_len respectively. */ if (total_subobj_len < 4) goto invalid; subobj_len = EXTRACT_16BITS(obj_tptr); subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u", ident, tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type), subobj_type, tok2str(af_values, "Unknown", af), af, subobj_len)); /* In addition to what is explained above, the same spec does not * explicitly say that the same Length field includes the 4-octet * sub-object header, but as long as this while loop implements it * as it does include, let's keep the check below consistent with * the rest of the code. */ if(subobj_len < 4 || subobj_len > total_subobj_len) goto invalid; switch(subobj_type) { case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: switch(af) { case AFNUM_INET: if (subobj_len < 8) return -1; ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s", ident, ipaddr_string(ndo, obj_tptr + 4))); break; case AFNUM_INET6: if (subobj_len < 20) return -1; ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s", ident, ip6addr_string(ndo, obj_tptr + 4))); break; case AFNUM_NSAP: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; } break; case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: if (subobj_len < 16) { return -1; } ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u", ident, ((EXTRACT_32BITS(obj_tptr+4))>>31), ((EXTRACT_32BITS(obj_tptr+4))&0xFF), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr + 12))); break; case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: if (subobj_len < 8) { return -1; } ND_PRINT((ndo, "%s Service level: %u", ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); break; default: hexdump=TRUE; break; } total_subobj_len-=subobj_len; obj_tptr+=subobj_len; obj_tlen+=subobj_len; } if (total_subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_RSVP_HOP: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; if (obj_tlen) hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 16))); obj_tlen-=20; obj_tptr+=20; hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; default: hexdump=TRUE; } break; case RSVP_OBJ_TIME_VALUES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Refresh Period: %ums", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; /* those three objects do share the same semantics */ case RSVP_OBJ_SENDER_TSPEC: case RSVP_OBJ_ADSPEC: case RSVP_OBJ_FLOWSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Msg-Version: %u, length: %u", ident, (*obj_tptr & 0xf0) >> 4, EXTRACT_16BITS(obj_tptr + 2) << 2)); obj_tptr+=4; /* get to the start of the service header */ obj_tlen-=4; while (obj_tlen >= 4) { intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u", ident, tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)), *(obj_tptr), (*(obj_tptr+1)&0x80) ? "" : "not", intserv_serv_tlen)); obj_tptr+=4; /* get to the start of the parameter list */ obj_tlen-=4; while (intserv_serv_tlen>=4) { processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); if (processed == 0) break; obj_tlen-=processed; intserv_serv_tlen-=processed; obj_tptr+=processed; } } break; default: hexdump=TRUE; } break; case RSVP_OBJ_FILTERSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_3: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_24BITS(obj_tptr + 17))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_FASTREROUTE: /* the differences between c-type 1 and 7 are minor */ obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: /* new style */ if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); obj_tlen-=sizeof(struct rsvp_obj_frr_t); obj_tptr+=sizeof(struct rsvp_obj_frr_t); break; case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ if (obj_tlen < 16) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_DETOUR: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: while(obj_tlen >= 8) { ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s", ident, ipaddr_string(ndo, obj_tptr), ipaddr_string(ndo, obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_CLASSTYPE: case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: ND_PRINT((ndo, "%s CT: %u", ident, EXTRACT_32BITS(obj_tptr) & 0x7)); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_ERROR_SPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; error_code=*(obj_tptr+5); error_value=EXTRACT_16BITS(obj_tptr+6); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr+4), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value), error_value)); break; default: ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value)); break; } obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; error_code=*(obj_tptr+17); error_value=EXTRACT_16BITS(obj_tptr+18); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr+16), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; default: break; } obj_tlen-=20; obj_tptr+=20; break; default: hexdump=TRUE; } break; case RSVP_OBJ_PROPERTIES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; padbytes = EXTRACT_16BITS(obj_tptr+2); ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u", ident, EXTRACT_16BITS(obj_tptr), padbytes)); obj_tlen-=4; obj_tptr+=4; /* loop through as long there is anything longer than the TLV header (2) */ while(obj_tlen >= 2 + padbytes) { ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */ ident, tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr), *obj_tptr, *(obj_tptr + 1))); if (obj_tlen < *(obj_tptr+1)) return-1; if (*(obj_tptr+1) < 2) return -1; print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2); obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_MESSAGE_ID: /* fall through */ case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ case RSVP_OBJ_MESSAGE_ID_LIST: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u", ident, *obj_tptr, EXTRACT_24BITS(obj_tptr + 1))); obj_tlen-=4; obj_tptr+=4; /* loop through as long there are no messages left */ while(obj_tlen >= 4) { ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_INTEGRITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) return-1; obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]", ident, EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), bittok2str(rsvp_obj_integrity_flag_values, "none", obj_ptr.rsvp_obj_integrity->flags))); ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); sigcheck = signature_verify(ndo, pptr, plen, obj_ptr.rsvp_obj_integrity->digest, rsvp_clear_checksum, rsvp_com_header); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); obj_tlen+=sizeof(struct rsvp_obj_integrity_t); obj_tptr+=sizeof(struct rsvp_obj_integrity_t); break; default: hexdump=TRUE; } break; case RSVP_OBJ_ADMIN_STATUS: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Flags [%s]", ident, bittok2str(rsvp_obj_admin_status_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_SET: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; action = (EXTRACT_16BITS(obj_tptr)>>8); ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident, tok2str(rsvp_obj_label_set_action_values, "Unknown", action), action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); switch (action) { case LABEL_SET_INCLUSIVE_RANGE: case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ /* only a couple of subchannels are expected */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: obj_tlen-=4; obj_tptr+=4; subchannel = 1; while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel, EXTRACT_32BITS(obj_tptr))); obj_tptr+=4; obj_tlen-=4; subchannel++; } break; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_S2L: switch (rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case RSVP_OBJ_SCOPE: case RSVP_OBJ_POLICY_DATA: case RSVP_OBJ_ACCEPT_LABEL_SET: case RSVP_OBJ_PROTECTION: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */ break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || hexdump == TRUE) print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */ rsvp_obj_len - sizeof(struct rsvp_object_header)); tptr+=rsvp_obj_len; tlen-=rsvp_obj_len; } return 0; invalid: ND_PRINT((ndo, "%s", istr)); return -1; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return -1; } void rsvp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct rsvp_common_header *rsvp_com_header; const u_char *tptr; u_short plen, tlen; tptr=pptr; rsvp_com_header = (const struct rsvp_common_header *)pptr; ND_TCHECK(*rsvp_com_header); /* * Sanity checking of the header. */ if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) { ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "RSVPv%u %s Message, length: %u", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags), tok2str(rsvp_msg_type_values, "unknown (%u)",rsvp_com_header->msg_type), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ plen = tlen = EXTRACT_16BITS(rsvp_com_header->length); ND_PRINT((ndo, "\n\tRSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags), tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type), rsvp_com_header->msg_type, bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)), tlen, rsvp_com_header->ttl, EXTRACT_16BITS(rsvp_com_header->checksum))); if (tlen < sizeof(const struct rsvp_common_header)) { ND_PRINT((ndo, "ERROR: common header too short %u < %lu", tlen, (unsigned long)sizeof(const struct rsvp_common_header))); return; } tptr+=sizeof(const struct rsvp_common_header); tlen-=sizeof(const struct rsvp_common_header); switch(rsvp_com_header->msg_type) { case RSVP_MSGTYPE_BUNDLE: /* * Process each submessage in the bundle message. * Bundle messages may not contain bundle submessages, so we don't * need to handle bundle submessages specially. */ while(tlen > 0) { const u_char *subpptr=tptr, *subtptr; u_short subplen, subtlen; subtptr=subpptr; rsvp_com_header = (const struct rsvp_common_header *)subpptr; ND_TCHECK(*rsvp_com_header); /* * Sanity checking of the header. */ if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) { ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags))); return; } subplen = subtlen = EXTRACT_16BITS(rsvp_com_header->length); ND_PRINT((ndo, "\n\t RSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags), tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type), rsvp_com_header->msg_type, bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)), subtlen, rsvp_com_header->ttl, EXTRACT_16BITS(rsvp_com_header->checksum))); if (subtlen < sizeof(const struct rsvp_common_header)) { ND_PRINT((ndo, "ERROR: common header too short %u < %lu", subtlen, (unsigned long)sizeof(const struct rsvp_common_header))); return; } if (tlen < subtlen) { ND_PRINT((ndo, "ERROR: common header too large %u > %u", subtlen, tlen)); return; } subtptr+=sizeof(const struct rsvp_common_header); subtlen-=sizeof(const struct rsvp_common_header); /* * Print all objects in the submessage. */ if (rsvp_obj_print(ndo, subpptr, subplen, subtptr, "\n\t ", subtlen, rsvp_com_header) == -1) return; tptr+=subtlen+sizeof(const struct rsvp_common_header); tlen-=subtlen+sizeof(const struct rsvp_common_header); } break; case RSVP_MSGTYPE_PATH: case RSVP_MSGTYPE_RESV: case RSVP_MSGTYPE_PATHERR: case RSVP_MSGTYPE_RESVERR: case RSVP_MSGTYPE_PATHTEAR: case RSVP_MSGTYPE_RESVTEAR: case RSVP_MSGTYPE_RESVCONF: case RSVP_MSGTYPE_HELLO_OLD: case RSVP_MSGTYPE_HELLO: case RSVP_MSGTYPE_ACK: case RSVP_MSGTYPE_SREFRESH: /* * Print all objects in the message. */ if (rsvp_obj_print(ndo, pptr, plen, tptr, "\n\t ", tlen, rsvp_com_header) == -1) return; break; default: print_unknown_data(ndo, tptr, "\n\t ", tlen); break; } return; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2727_0
crossvul-cpp_data_good_3328_3
/* 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 <stdlib.h> #include <ctype.h> #include <yara/globals.h> #include <yara/limits.h> #include <yara/utils.h> #include <yara/re.h> #include <yara/types.h> #include <yara/error.h> #include <yara/libyara.h> #include <yara/scan.h> typedef struct _CALLBACK_ARGS { YR_STRING* string; YR_SCAN_CONTEXT* context; uint8_t* data; size_t data_size; size_t data_base; int forward_matches; int full_word; } CALLBACK_ARGS; int _yr_scan_compare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length) return 0; while (i < string_length && *s1++ == *s2++) i++; return (int) ((i == string_length) ? i : 0); } int _yr_scan_icompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length) return 0; while (i < string_length && yr_lowercase[*s1++] == yr_lowercase[*s2++]) i++; return (int) ((i == string_length) ? i : 0); } int _yr_scan_wcompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length * 2) return 0; while (i < string_length && *s1 == *s2) { s1+=2; s2++; i++; } return (int) ((i == string_length) ? i * 2 : 0); } int _yr_scan_wicompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length * 2) return 0; while (i < string_length && yr_lowercase[*s1] == yr_lowercase[*s2]) { s1+=2; s2++; i++; } return (int) ((i == string_length) ? i * 2 : 0); } void _yr_scan_update_match_chain_length( int tidx, YR_STRING* string, YR_MATCH* match_to_update, int chain_length) { YR_MATCH* match; if (match_to_update->chain_length == chain_length) return; match_to_update->chain_length = chain_length; if (string->chained_to == NULL) return; match = string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { int64_t ending_offset = match->offset + match->match_length; if (ending_offset + string->chain_gap_max >= match_to_update->offset && ending_offset + string->chain_gap_min <= match_to_update->offset) { _yr_scan_update_match_chain_length( tidx, string->chained_to, match, chain_length + 1); } match = match->next; } } int _yr_scan_add_match_to_list( YR_MATCH* match, YR_MATCHES* matches_list, int replace_if_exists) { YR_MATCH* insertion_point = matches_list->tail; if (matches_list->count == MAX_STRING_MATCHES) return ERROR_TOO_MANY_MATCHES; while (insertion_point != NULL) { if (match->offset == insertion_point->offset) { if (replace_if_exists) { insertion_point->match_length = match->match_length; insertion_point->data_length = match->data_length; insertion_point->data = match->data; } return ERROR_SUCCESS; } if (match->offset > insertion_point->offset) break; insertion_point = insertion_point->prev; } match->prev = insertion_point; if (insertion_point != NULL) { match->next = insertion_point->next; insertion_point->next = match; } else { match->next = matches_list->head; matches_list->head = match; } matches_list->count++; if (match->next != NULL) match->next->prev = match; else matches_list->tail = match; return ERROR_SUCCESS; } void _yr_scan_remove_match_from_list( YR_MATCH* match, YR_MATCHES* matches_list) { if (match->prev != NULL) match->prev->next = match->next; if (match->next != NULL) match->next->prev = match->prev; if (matches_list->head == match) matches_list->head = match->next; if (matches_list->tail == match) matches_list->tail = match->prev; matches_list->count--; match->next = NULL; match->prev = NULL; } int _yr_scan_verify_chained_string_match( YR_STRING* matching_string, YR_SCAN_CONTEXT* context, uint8_t* match_data, uint64_t match_base, uint64_t match_offset, int32_t match_length) { YR_STRING* string; YR_MATCH* match; YR_MATCH* next_match; YR_MATCH* new_match; uint64_t lower_offset; uint64_t ending_offset; int32_t full_chain_length; int tidx = context->tidx; int add_match = FALSE; if (matching_string->chained_to == NULL) { add_match = TRUE; } else { if (matching_string->unconfirmed_matches[tidx].head != NULL) lower_offset = matching_string->unconfirmed_matches[tidx].head->offset; else lower_offset = match_offset; match = matching_string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { next_match = match->next; ending_offset = match->offset + match->match_length; if (ending_offset + matching_string->chain_gap_max < lower_offset) { _yr_scan_remove_match_from_list( match, &matching_string->chained_to->unconfirmed_matches[tidx]); } else { if (ending_offset + matching_string->chain_gap_max >= match_offset && ending_offset + matching_string->chain_gap_min <= match_offset) { add_match = TRUE; break; } } match = next_match; } } if (add_match) { if (STRING_IS_CHAIN_TAIL(matching_string)) { // Chain tails must be chained to some other string assert(matching_string->chained_to != NULL); match = matching_string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { ending_offset = match->offset + match->match_length; if (ending_offset + matching_string->chain_gap_max >= match_offset && ending_offset + matching_string->chain_gap_min <= match_offset) { _yr_scan_update_match_chain_length( tidx, matching_string->chained_to, match, 1); } match = match->next; } full_chain_length = 0; string = matching_string; while(string->chained_to != NULL) { full_chain_length++; string = string->chained_to; } // "string" points now to the head of the strings chain match = string->unconfirmed_matches[tidx].head; while (match != NULL) { next_match = match->next; if (match->chain_length == full_chain_length) { _yr_scan_remove_match_from_list( match, &string->unconfirmed_matches[tidx]); match->match_length = (int32_t) \ (match_offset - match->offset + match_length); match->data_length = yr_min(match->match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( context->matches_arena, match_data - match_offset + match->offset, match->data_length, (void**) &match->data)); FAIL_ON_ERROR(_yr_scan_add_match_to_list( match, &string->matches[tidx], FALSE)); } match = next_match; } } else { if (matching_string->matches[tidx].count == 0 && matching_string->unconfirmed_matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( context->matching_strings_arena, &matching_string, sizeof(matching_string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); new_match->base = match_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->chain_length = 0; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &matching_string->unconfirmed_matches[tidx], FALSE)); } } return ERROR_SUCCESS; } int _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; // total match length is the sum of backward and forward matches. match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; } typedef int (*RE_EXEC_FUNC)( uint8_t* code, uint8_t* input, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args); int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL); } switch(forward_matches) { case -1: return ERROR_SUCCESS; case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { backward_matches = exec( ac_match->backward_code, data + offset, data_size - offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args); switch(backward_matches) { case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; } int _yr_scan_verify_literal_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { int flags = 0; int forward_matches = 0; CALLBACK_ARGS callback_args; YR_STRING* string = ac_match->string; if (STRING_FITS_IN_ATOM(string)) { forward_matches = ac_match->backtrack; } else if (STRING_IS_NO_CASE(string)) { if (STRING_IS_ASCII(string)) { forward_matches = _yr_scan_icompare( data + offset, data_size - offset, string->string, string->length); } if (STRING_IS_WIDE(string) && forward_matches == 0) { forward_matches = _yr_scan_wicompare( data + offset, data_size - offset, string->string, string->length); } } else { if (STRING_IS_ASCII(string)) { forward_matches = _yr_scan_compare( data + offset, data_size - offset, string->string, string->length); } if (STRING_IS_WIDE(string) && forward_matches == 0) { forward_matches = _yr_scan_wcompare( data + offset, data_size - offset, string->string, string->length); } } if (forward_matches == 0) return ERROR_SUCCESS; if (forward_matches == string->length * 2) flags |= RE_FLAGS_WIDE; if (STRING_IS_NO_CASE(string)) flags |= RE_FLAGS_NO_CASE; callback_args.context = context; callback_args.string = string; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(string); FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); return ERROR_SUCCESS; } int yr_scan_verify_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { YR_STRING* string = ac_match->string; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif if (data_size - offset <= 0) return ERROR_SUCCESS; if (context->flags & SCAN_FLAGS_FAST_MODE && STRING_IS_SINGLE_MATCH(string) && string->matches[context->tidx].head != NULL) return ERROR_SUCCESS; if (STRING_IS_FIXED_OFFSET(string) && string->fixed_offset != data_base + offset) return ERROR_SUCCESS; if (STRING_IS_LITERAL(string)) { FAIL_ON_ERROR(_yr_scan_verify_literal_match( context, ac_match, data, data_size, data_base, offset)); } else { FAIL_ON_ERROR(_yr_scan_verify_re_match( context, ac_match, data, data_size, data_base, offset)); } #ifdef PROFILING_ENABLED string->clock_ticks += clock() - start; #endif return ERROR_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3328_3
crossvul-cpp_data_good_1854_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS U U N N % % SS U U NN N % % SSS U U N N N % % SS U U N NN % % SSSSS UUU N N % % % % % % Read/Write Sun Rasterfile Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 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/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/colormap.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/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S U N % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSUN() returns MagickTrue if the image format type, identified by the % magick string, is SUN. % % The format of the IsSUN method is: % % MagickBooleanType IsSUN(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 IsSUN(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\131\246\152\225",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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(const unsigned char *compressed_pixels, % const size_t length,unsigned char *pixels) % % A description of each parameter follows: % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % % o length: An integer value that is the total number of bytes of the % source image (as just read by ReadBlob) % % o pixels: The address of a byte (8 bits) array of pixel data created by % the uncompression process. The number of bytes in this array % must be at least equal to the number columns times the number of rows % of the source pixels. % */ static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, const size_t length,unsigned char *pixels,size_t maxpixels) { register const unsigned char *l, *p; register unsigned char *q; ssize_t count; unsigned char byte; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(compressed_pixels != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); p=compressed_pixels; q=pixels; l=q+maxpixels; while (((size_t) (p-compressed_pixels) < length) && (q < l)) { byte=(*p++); if (byte != 128U) *q++=byte; else { /* Runlength-encoded packet: <count><byte> */ count=(ssize_t) (*p++); if (count > 0) byte=(*p++); while ((count >= 0) && (q < l)) { *q++=byte; count--; } } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSUNImage() reads a SUN 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 ReadSUNImage method is: % % Image *ReadSUNImage(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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_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,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); sun_pixels=sun_data; bytes_per_line=0; if (sun_info.type == RT_ENCODED) { size_t height; /* Read run-length encoded raster pixels. */ height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); } /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { 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=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+bytes_per_line % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", 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; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSUNImage() adds attributes for the SUN 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 RegisterSUNImage method is: % % size_t RegisterSUNImage(void) % */ ModuleExport size_t RegisterSUNImage(void) { MagickInfo *entry; entry=SetMagickInfo("RAS"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->magick=(IsImageFormatHandler *) IsSUN; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SUN"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSUNImage() removes format registrations made by the % SUN module from the list of supported formats. % % The format of the UnregisterSUNImage method is: % % UnregisterSUNImage(void) % */ ModuleExport void UnregisterSUNImage(void) { (void) UnregisterMagickInfo("RAS"); (void) UnregisterMagickInfo("SUN"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSUNImage() writes an image in the SUN rasterfile format. % % The format of the WriteSUNImage method is: % % MagickBooleanType WriteSUNImage(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 WriteSUNImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; register const Quantum *p; register ssize_t i, x; ssize_t y; SUNInfo sun_info; /* 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SUN raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); sun_info.magic=0x59a66a95; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); sun_info.width=(unsigned int) image->columns; sun_info.height=(unsigned int) image->rows; sun_info.type=(unsigned int) (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD); sun_info.maptype=RMT_NONE; sun_info.maplength=0; number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (size_t) (4*number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (image->storage_class == DirectClass) { /* Full color SUN raster. */ sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ? 32U : 24U; sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ? 4 : 3)*number_pixels); sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows : 0; } else if (IsImageMonochrome(image,exception) != MagickFalse) { /* Monochrome SUN raster. */ sun_info.depth=1; sun_info.length=(unsigned int) (((image->columns+7) >> 3)* image->rows); sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2 ? image->rows : 0); } else { /* Colormapped SUN raster. */ sun_info.depth=8; sun_info.length=(unsigned int) number_pixels; sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows : 0); sun_info.maptype=RMT_EQUAL_RGB; sun_info.maplength=(unsigned int) (3*image->colors); } /* Write SUN header. */ (void) WriteBlobMSBLong(image,sun_info.magic); (void) WriteBlobMSBLong(image,sun_info.width); (void) WriteBlobMSBLong(image,sun_info.height); (void) WriteBlobMSBLong(image,sun_info.depth); (void) WriteBlobMSBLong(image,sun_info.length); (void) WriteBlobMSBLong(image,sun_info.type); (void) WriteBlobMSBLong(image,sun_info.maptype); (void) WriteBlobMSBLong(image,sun_info.maplength); /* Convert MIFF to SUN raster pixels. */ x=0; y=0; if (image->storage_class == DirectClass) { register unsigned char *q; size_t bytes_per_pixel, length; unsigned char *pixels; /* Allocate memory for pixels. */ bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; length=image->columns; pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert DirectClass packet to SUN RGB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) & 0x01) != 0) *q++='\0'; /* pad scanline */ (void) WriteBlob(image,(size_t) (q-pixels),pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } else if (IsImageMonochrome(image,exception) != MagickFalse) { register unsigned char bit, byte; /* Convert PseudoClass image to a SUN monochrome image. */ (void) SetImageType(image,BilevelType,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,byte); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); if ((((image->columns/8)+ (image->columns % 8 ? 1 : 0)) % 2) != 0) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Dump colormap to file. */ for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); /* Convert PseudoClass packet to SUN colormapped pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->columns & 0x01) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1854_0
crossvul-cpp_data_bad_351_6
/* * 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[8] = { 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, 8); 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, unsigned char *out, size_t * out_len) { size_t in_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]) { in_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { in_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { in_len = in[2] * 0x100; in_len += in[3]; i = 5; } else { return -1; } /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[in_len - 2] && (in_len - 2 > 0)) in_len--; if (2 == in_len) return -1; memcpy(out, plaintext, in_len - 2); *out_len = in_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, 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-125/c/bad_351_6
crossvul-cpp_data_good_2700_0
/* * Copyright (C) 2002 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ /* \summary: IPv6 mobility printer */ /* RFC 3775 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip6.h" static const char tstr[] = "[|MOBILITY]"; /* Mobility header */ struct ip6_mobility { uint8_t ip6m_pproto; /* following payload protocol (for PG) */ uint8_t ip6m_len; /* length in units of 8 octets */ uint8_t ip6m_type; /* message type */ uint8_t reserved; /* reserved */ uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */ union { uint16_t ip6m_un_data16[1]; /* type-specific field */ uint8_t ip6m_un_data8[2]; /* type-specific field */ } ip6m_dataun; }; #define ip6m_data16 ip6m_dataun.ip6m_un_data16 #define ip6m_data8 ip6m_dataun.ip6m_un_data8 #define IP6M_MINLEN 8 /* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */ /* message type */ #define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */ #define IP6M_HOME_TEST_INIT 1 /* Home Test Init */ #define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */ #define IP6M_HOME_TEST 3 /* Home Test */ #define IP6M_CAREOF_TEST 4 /* Care-of Test */ #define IP6M_BINDING_UPDATE 5 /* Binding Update */ #define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */ #define IP6M_BINDING_ERROR 7 /* Binding Error */ #define IP6M_MAX 7 static const struct tok ip6m_str[] = { { IP6M_BINDING_REQUEST, "BRR" }, { IP6M_HOME_TEST_INIT, "HoTI" }, { IP6M_CAREOF_TEST_INIT, "CoTI" }, { IP6M_HOME_TEST, "HoT" }, { IP6M_CAREOF_TEST, "CoT" }, { IP6M_BINDING_UPDATE, "BU" }, { IP6M_BINDING_ACK, "BA" }, { IP6M_BINDING_ERROR, "BE" }, { 0, NULL } }; static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = { IP6M_MINLEN, /* IP6M_BINDING_REQUEST */ IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */ IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */ IP6M_MINLEN + 16, /* IP6M_HOME_TEST */ IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */ IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */ IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */ IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */ }; /* Mobility Header Options */ #define IP6MOPT_MINLEN 2 #define IP6MOPT_PAD1 0x0 /* Pad1 */ #define IP6MOPT_PADN 0x1 /* PadN */ #define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */ #define IP6MOPT_REFRESH_MINLEN 4 #define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */ #define IP6MOPT_ALTCOA_MINLEN 18 #define IP6MOPT_NONCEID 0x4 /* Nonce Indices */ #define IP6MOPT_NONCEID_MINLEN 6 #define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */ #define IP6MOPT_AUTH_MINLEN 12 static int mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_TCHECK_16BITS(&bp[i+2]); ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_TCHECK_16BITS(&bp[i+2]); ND_TCHECK_16BITS(&bp[i+4]); ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } /* * Mobility Header */ int mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK_16BITS(&bp[hlen]); if (bp[hlen] & 0xf0) { ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); } /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK_16BITS(&bp[hlen]); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); ND_TCHECK(mh->ip6m_data8[1]); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK_16BITS(&bp[hlen]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK_16BITS(&bp[hlen]); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(bp[hlen], 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2700_0
crossvul-cpp_data_good_2644_9
/* * Copyright (C) 2001 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. */ /* \summary: Multi-Protocol Label Switching (MPLS) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "mpls.h" static const char *mpls_labelname[] = { /*0*/ "IPv4 explicit NULL", "router alert", "IPv6 explicit NULL", "implicit NULL", "rsvd", /*5*/ "rsvd", "rsvd", "rsvd", "rsvd", "rsvd", /*10*/ "rsvd", "rsvd", "rsvd", "rsvd", "rsvd", /*15*/ "rsvd", }; enum mpls_packet_type { PT_UNKNOWN, PT_IPV4, PT_IPV6, PT_OSI }; /* * RFC3032: MPLS label stack encoding */ void mpls_print(netdissect_options *ndo, const u_char *bp, u_int length) { const u_char *p; uint32_t label_entry; uint16_t label_stack_depth = 0; enum mpls_packet_type pt = PT_UNKNOWN; p = bp; ND_PRINT((ndo, "MPLS")); do { ND_TCHECK2(*p, sizeof(label_entry)); if (length < sizeof(label_entry)) { ND_PRINT((ndo, "[|MPLS], length %u", length)); return; } label_entry = EXTRACT_32BITS(p); ND_PRINT((ndo, "%s(label %u", (label_stack_depth && ndo->ndo_vflag) ? "\n\t" : " ", MPLS_LABEL(label_entry))); label_stack_depth++; if (ndo->ndo_vflag && MPLS_LABEL(label_entry) < sizeof(mpls_labelname) / sizeof(mpls_labelname[0])) ND_PRINT((ndo, " (%s)", mpls_labelname[MPLS_LABEL(label_entry)])); ND_PRINT((ndo, ", exp %u", MPLS_EXP(label_entry))); if (MPLS_STACK(label_entry)) ND_PRINT((ndo, ", [S]")); ND_PRINT((ndo, ", ttl %u)", MPLS_TTL(label_entry))); p += sizeof(label_entry); length -= sizeof(label_entry); } while (!MPLS_STACK(label_entry)); /* * Try to figure out the packet type. */ switch (MPLS_LABEL(label_entry)) { case 0: /* IPv4 explicit NULL label */ case 3: /* IPv4 implicit NULL label */ pt = PT_IPV4; break; case 2: /* IPv6 explicit NULL label */ pt = PT_IPV6; break; default: /* * Generally there's no indication of protocol in MPLS label * encoding. * * However, draft-hsmit-isis-aal5mux-00.txt describes a * technique for encapsulating IS-IS and IP traffic on the * same ATM virtual circuit; you look at the first payload * byte to determine the network layer protocol, based on * the fact that * * 1) the first byte of an IP header is 0x45-0x4f * for IPv4 and 0x60-0x6f for IPv6; * * 2) the first byte of an OSI CLNP packet is 0x81, * the first byte of an OSI ES-IS packet is 0x82, * and the first byte of an OSI IS-IS packet is * 0x83; * * so the network layer protocol can be inferred from the * first byte of the packet, if the protocol is one of the * ones listed above. * * Cisco sends control-plane traffic MPLS-encapsulated in * this fashion. */ ND_TCHECK(*p); if (length < 1) { /* nothing to print */ return; } switch(*p) { case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: pt = PT_IPV4; break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: pt = PT_IPV6; break; case 0x81: case 0x82: case 0x83: pt = PT_OSI; break; default: /* ok bail out - we did not figure out what it is*/ break; } } /* * Print the payload. */ if (pt == PT_UNKNOWN) { if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, length); return; } ND_PRINT((ndo, ndo->ndo_vflag ? "\n\t" : " ")); switch (pt) { case PT_IPV4: ip_print(ndo, p, length); break; case PT_IPV6: ip6_print(ndo, p, length); break; case PT_OSI: isoclns_print(ndo, p, length); break; default: break; } return; trunc: ND_PRINT((ndo, "[|MPLS]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_9
crossvul-cpp_data_bad_766_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L OOO CCCC AAA L EEEEE % % L O O C A A L E % % L O O C AAAAA L EEE % % L O O C A A L E % % LLLLL OOO CCCC A A LLLLL EEEEE % % % % % % MagickCore Image Locale Methods % % % % Software Design % % Cristy % % July 2003 % % % % % % 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/blob.h" #include "MagickCore/client.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image-private.h" #include "MagickCore/linked-list.h" #include "MagickCore/locale_.h" #include "MagickCore/locale-private.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #if defined(MAGICKCORE_HAVE_NEWLOCALE) || defined(MAGICKCORE_WINDOWS_SUPPORT) # define MAGICKCORE_LOCALE_SUPPORT #endif #define LocaleFilename "locale.xml" /* Static declarations. */ static const char *LocaleMap = "<?xml version=\"1.0\"?>" "<localemap>" " <locale name=\"C\">" " <Exception>" " <Message name=\"\">" " </Message>" " </Exception>" " </locale>" "</localemap>"; #ifdef __VMS #define asciimap AsciiMap #endif #if !defined(MAGICKCORE_HAVE_STRCASECMP) || !defined(MAGICKCORE_HAVE_STRNCASECMP) static const unsigned char AsciiMap[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xc5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }; #endif static SemaphoreInfo *locale_semaphore = (SemaphoreInfo *) NULL; static SplayTreeInfo *locale_cache = (SplayTreeInfo *) NULL; #if defined(MAGICKCORE_LOCALE_SUPPORT) static volatile locale_t c_locale = (locale_t) NULL; #endif /* Forward declarations. */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *), LoadLocaleCache(SplayTreeInfo *,const char *,const char *,const char *, const size_t,ExceptionInfo *); #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCLocale() allocates the C locale object, or (locale_t) 0 with % errno set if it cannot be acquired. % % The format of the AcquireCLocale method is: % % locale_t AcquireCLocale(void) % */ static locale_t AcquireCLocale(void) { #if defined(MAGICKCORE_HAVE_NEWLOCALE) if (c_locale == (locale_t) NULL) c_locale=newlocale(LC_ALL_MASK,"C",(locale_t) 0); #elif defined(MAGICKCORE_WINDOWS_SUPPORT) && !defined(__MINGW32__) if (c_locale == (locale_t) NULL) c_locale=_create_locale(LC_ALL,"C"); #endif return(c_locale); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e L o c a l e S p l a y T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireLocaleSplayTree() caches one or more locale configurations which % provides a mapping between locale attributes and a locale tag. % % The format of the AcquireLocaleSplayTree method is: % % SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the font file tag. % % o locale: the actual locale. % % o exception: return any errors or warnings in this structure. % */ static void *DestroyLocaleNode(void *locale_info) { register LocaleInfo *p; p=(LocaleInfo *) locale_info; if (p->path != (char *) NULL) p->path=DestroyString(p->path); if (p->tag != (char *) NULL) p->tag=DestroyString(p->tag); if (p->message != (char *) NULL) p->message=DestroyString(p->message); return(RelinquishMagickMemory(p)); } static SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, const char *locale,ExceptionInfo *exception) { MagickStatusType status; SplayTreeInfo *cache; cache=NewSplayTree(CompareSplayTreeString,(void *(*)(void *)) NULL, DestroyLocaleNode); status=MagickTrue; #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) { const StringInfo *option; LinkedListInfo *options; options=GetLocaleOptions(filename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); if (GetNumberOfNodesInSplayTree(cache) == 0) { options=GetLocaleOptions("english.xml",exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); } } #endif if (GetNumberOfNodesInSplayTree(cache) == 0) status&=LoadLocaleCache(cache,LocaleMap,"built-in",locale,0, exception); return(cache); } #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCLocale() releases the resources allocated for a locale object % returned by a call to the AcquireCLocale() method. % % The format of the DestroyCLocale method is: % % void DestroyCLocale(void) % */ static void DestroyCLocale(void) { if (c_locale != (locale_t) NULL) freelocale(c_locale); c_locale=(locale_t) NULL; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyLocaleOptions() releases memory associated with an locale % messages. % % The format of the DestroyProfiles method is: % % LinkedListInfo *DestroyLocaleOptions(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *DestroyOptions(void *message) { return(DestroyStringInfo((StringInfo *) message)); } MagickExport LinkedListInfo *DestroyLocaleOptions(LinkedListInfo *messages) { assert(messages != (LinkedListInfo *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); return(DestroyLinkedList(messages,DestroyOptions)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleFile() prints formatted output of a variable argument list to a % file in the "C" locale. % % The format of the FormatLocaleFile method is: % % ssize_t FormatLocaleFile(FILE *file,const char *format,...) % % A description of each parameter follows. % % o file: the file. % % o format: A file describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleFileList(FILE *file, const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VFPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vfprintf_l(file,format,locale,operands); #else n=(ssize_t) vfprintf_l(file,locale,format,operands); #endif } #else #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vfprintf(file,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vfprintf(file,format,operands); #endif #endif return(n); } MagickExport ssize_t FormatLocaleFile(FILE *file, const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleFileList(file,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleString() prints formatted output of a variable argument list to % a string buffer in the "C" locale. % % The format of the FormatLocaleString method is: % % ssize_t FormatLocaleString(char *string,const size_t length, % const char *format,...) % % A description of each parameter follows. % % o string: FormatLocaleString() returns the formatted string in this % character buffer. % % o length: the maximum length of the string. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleStringList(char *magick_restrict string, const size_t length,const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VSNPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vsnprintf_l(string,length,format,locale,operands); #else n=(ssize_t) vsnprintf_l(string,length,locale,format,operands); #endif } #elif defined(MAGICKCORE_HAVE_VSNPRINTF) #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vsnprintf(string,length,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vsnprintf(string,length,format,operands); #endif #else n=(ssize_t) vsprintf(string,format,operands); #endif if (n < 0) string[length-1]='\0'; return(n); } MagickExport ssize_t FormatLocaleString(char *magick_restrict string, const size_t length,const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(string,length,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t L o c a l e I n f o _ % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfo_() searches the locale list for the specified tag and if % found returns attributes for that element. % % The format of the GetLocaleInfo method is: % % const LocaleInfo *GetLocaleInfo_(const char *tag, % ExceptionInfo *exception) % % A description of each parameter follows: % % o tag: the locale tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport const LocaleInfo *GetLocaleInfo_(const char *tag, ExceptionInfo *exception) { const LocaleInfo *locale_info; assert(exception != (ExceptionInfo *) NULL); if (IsLocaleTreeInstantiated(exception) == MagickFalse) return((const LocaleInfo *) NULL); LockSemaphoreInfo(locale_semaphore); if ((tag == (const char *) NULL) || (LocaleCompare(tag,"*") == 0)) { ResetSplayTreeIterator(locale_cache); locale_info=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } locale_info=(const LocaleInfo *) GetValueFromSplayTree(locale_cache,tag); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e I n f o L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfoList() returns any locale messages that match the % specified pattern. % % The format of the GetLocaleInfoList function is: % % const LocaleInfo **GetLocaleInfoList(const char *pattern, % size_t *number_messages,ExceptionInfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of locale messages in % the list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleInfoCompare(const void *x,const void *y) { const LocaleInfo **p, **q; p=(const LocaleInfo **) x, q=(const LocaleInfo **) y; if (LocaleCompare((*p)->path,(*q)->path) == 0) return(LocaleCompare((*p)->tag,(*q)->tag)); return(LocaleCompare((*p)->path,(*q)->path)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport const LocaleInfo **GetLocaleInfoList(const char *pattern, size_t *number_messages,ExceptionInfo *exception) { const LocaleInfo **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((const LocaleInfo **) NULL); messages=(const LocaleInfo **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (const LocaleInfo **) NULL) return((const LocaleInfo **) NULL); /* Generate locale list. */ LockSemaphoreInfo(locale_semaphore); ResetSplayTreeIterator(locale_cache); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=p; p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleInfoCompare); messages[i]=(LocaleInfo *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleList() returns any locale messages that match the specified % pattern. % % The format of the GetLocaleList function is: % % char **GetLocaleList(const char *pattern,size_t *number_messages, % Exceptioninfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of messages in the % list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleTagCompare(const void *x,const void *y) { register char **p, **q; p=(char **) x; q=(char **) y; return(LocaleCompare(*p,*q)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport char **GetLocaleList(const char *pattern,size_t *number_messages, ExceptionInfo *exception) { char **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((char **) NULL); messages=(char **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (char **) NULL) return((char **) NULL); LockSemaphoreInfo(locale_semaphore); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=ConstantString(p->tag); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleTagCompare); messages[i]=(char *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e M e s s a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleMessage() returns a message in the current locale that matches the % supplied tag. % % The format of the GetLocaleMessage method is: % % const char *GetLocaleMessage(const char *tag) % % A description of each parameter follows: % % o tag: Return a message that matches this tag in the current locale. % */ MagickExport const char *GetLocaleMessage(const char *tag) { char name[MagickLocaleExtent]; const LocaleInfo *locale_info; ExceptionInfo *exception; if ((tag == (const char *) NULL) || (*tag == '\0')) return(tag); exception=AcquireExceptionInfo(); (void) FormatLocaleString(name,MagickLocaleExtent,"%s/",tag); locale_info=GetLocaleInfo_(name,exception); exception=DestroyExceptionInfo(exception); if (locale_info != (const LocaleInfo *) NULL) return(locale_info->message); return(tag); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleOptions() returns any Magick configuration messages associated % with the specified filename. % % The format of the GetLocaleOptions method is: % % LinkedListInfo *GetLocaleOptions(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the locale file tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport LinkedListInfo *GetLocaleOptions(const char *filename, ExceptionInfo *exception) { char path[MagickPathExtent]; const char *element; LinkedListInfo *messages, *paths; StringInfo *xml; assert(filename != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename); assert(exception != (ExceptionInfo *) NULL); (void) CopyMagickString(path,filename,MagickPathExtent); /* Load XML from configuration files to linked-list. */ messages=NewLinkedList(0); paths=GetConfigurePaths(filename,exception); if (paths != (LinkedListInfo *) NULL) { ResetLinkedListIterator(paths); element=(const char *) GetNextValueInLinkedList(paths); while (element != (const char *) NULL) { (void) FormatLocaleString(path,MagickPathExtent,"%s%s",element, filename); (void) LogMagickEvent(LocaleEvent,GetMagickModule(), "Searching for locale file: \"%s\"",path); xml=ConfigureFileToStringInfo(path); if (xml != (StringInfo *) NULL) (void) AppendValueToLinkedList(messages,xml); element=(const char *) GetNextValueInLinkedList(paths); } paths=DestroyLinkedList(paths,RelinquishMagickMemory); } #if defined(MAGICKCORE_WINDOWS_SUPPORT) { char *blob; blob=(char *) NTResourceToBlob(filename); if (blob != (char *) NULL) { xml=AcquireStringInfo(0); SetStringInfoLength(xml,strlen(blob)+1); SetStringInfoDatum(xml,(const unsigned char *) blob); blob=(char *) RelinquishMagickMemory(blob); SetStringInfoPath(xml,filename); (void) AppendValueToLinkedList(messages,xml); } } #endif ResetLinkedListIterator(messages); return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleValue() returns the message associated with the locale info. % % The format of the GetLocaleValue method is: % % const char *GetLocaleValue(const LocaleInfo *locale_info) % % A description of each parameter follows: % % o locale_info: The locale info. % */ MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(locale_info != (LocaleInfo *) NULL); assert(locale_info->signature == MagickCoreSignature); return(locale_info->message); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s L o c a l e T r e e I n s t a n t i a t e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsLocaleTreeInstantiated() determines if the locale tree is instantiated. % If not, it instantiates the tree and returns it. % % The format of the IsLocaleInstantiated method is: % % MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) % % A description of each parameter follows. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) { if (locale_cache == (SplayTreeInfo *) NULL) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache == (SplayTreeInfo *) NULL) { char *locale; register const char *p; locale=(char *) NULL; p=setlocale(LC_CTYPE,(const char *) NULL); if (p != (const char *) NULL) locale=ConstantString(p); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_ALL"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_MESSAGES"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_CTYPE"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LANG"); if (locale == (char *) NULL) locale=ConstantString("C"); locale_cache=AcquireLocaleSplayTree(LocaleFilename,locale,exception); locale=DestroyString(locale); } UnlockSemaphoreInfo(locale_semaphore); } return(locale_cache != (SplayTreeInfo *) NULL ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n t e r p r e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretLocaleValue() interprets the string as a floating point number in % the "C" locale and returns its value as a double. If sentinal is not a null % pointer, the method also sets the value pointed by sentinal to point to the % first character after the number. % % The format of the InterpretLocaleValue method is: % % double InterpretLocaleValue(const char *value,char **sentinal) % % A description of each parameter follows: % % o value: the string value. % % o sentinal: if sentinal is not NULL, a pointer to the character after the % last character used in the conversion is stored in the location % referenced by sentinal. % */ MagickExport double InterpretLocaleValue(const char *magick_restrict string, char **magick_restrict sentinal) { char *q; double value; if ((*string == '0') && ((string[1] | 0x20)=='x')) value=(double) strtoul(string,&q,16); else { #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_STRTOD_L) locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) value=strtod(string,&q); else value=strtod_l(string,&q,locale); #else value=strtod(string,&q); #endif } if (sentinal != (char **) NULL) *sentinal=q; return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t L o c a l e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListLocaleInfo() lists the locale info to a file. % % The format of the ListLocaleInfo method is: % % MagickBooleanType ListLocaleInfo(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to a FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListLocaleInfo(FILE *file, ExceptionInfo *exception) { const char *path; const LocaleInfo **locale_info; register ssize_t i; size_t number_messages; if (file == (const FILE *) NULL) file=stdout; number_messages=0; locale_info=GetLocaleInfoList("*",&number_messages,exception); if (locale_info == (const LocaleInfo **) NULL) return(MagickFalse); path=(const char *) NULL; for (i=0; i < (ssize_t) number_messages; i++) { if (locale_info[i]->stealth != MagickFalse) continue; if ((path == (const char *) NULL) || (LocaleCompare(path,locale_info[i]->path) != 0)) { if (locale_info[i]->path != (char *) NULL) (void) FormatLocaleFile(file,"\nPath: %s\n\n",locale_info[i]->path); (void) FormatLocaleFile(file,"Tag/Message\n"); (void) FormatLocaleFile(file, "-------------------------------------------------" "------------------------------\n"); } path=locale_info[i]->path; (void) FormatLocaleFile(file,"%s\n",locale_info[i]->tag); if (locale_info[i]->message != (char *) NULL) (void) FormatLocaleFile(file," %s",locale_info[i]->message); (void) FormatLocaleFile(file,"\n"); } (void) fflush(file); locale_info=(const LocaleInfo **) RelinquishMagickMemory((void *) locale_info); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o a d L o c a l e C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LoadLocaleCache() loads the locale configurations which provides a mapping % between locale attributes and a locale name. % % The format of the LoadLocaleCache method is: % % MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, % const char *filename,const size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o xml: The locale list in XML format. % % o filename: The locale list filename. % % o depth: depth of <include /> statements. % % o exception: return any errors or warnings in this structure. % */ static void ChopLocaleComponents(char *path,const size_t components) { register char *p; ssize_t count; if (*path == '\0') return; p=path+strlen(path)-1; if (*p == '/') *p='\0'; for (count=0; (count < (ssize_t) components) && (p > path); p--) if (*p == '/') { *p='\0'; count++; } if (count < (ssize_t) components) *path='\0'; } static void LocaleFatalErrorHandler( const ExceptionType magick_unused(severity), const char *reason,const char *description) { magick_unreferenced(severity); if (reason == (char *) NULL) return; (void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason); if (description != (char *) NULL) (void) FormatLocaleFile(stderr," (%s)",description); (void) FormatLocaleFile(stderr,".\n"); (void) fflush(stderr); exit(1); } static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception) { char keyword[MagickLocaleExtent], message[MagickLocaleExtent], tag[MagickLocaleExtent], *token; const char *q; FatalErrorHandler fatal_handler; LocaleInfo *locale_info; MagickStatusType status; register char *p; size_t extent; /* Read the locale configure file. */ (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading locale configure file \"%s\" ...",filename); if (xml == (const char *) NULL) return(MagickFalse); status=MagickTrue; locale_info=(LocaleInfo *) NULL; *tag='\0'; *message='\0'; *keyword='\0'; fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler); token=AcquireString(xml); extent=strlen(token)+MagickPathExtent; for (q=(char *) xml; *q != '\0'; ) { /* Interpret XML. */ GetNextToken(q,&q,extent,token); if (*token == '\0') break; (void) CopyMagickString(keyword,token,MagickLocaleExtent); if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0) { /* Doctype element. */ while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleNCompare(keyword,"<!--",4) == 0) { /* Comment element. */ while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleCompare(keyword,"<include") == 0) { /* Include element. */ while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"locale") == 0) { if (LocaleCompare(locale,token) != 0) break; continue; } if (LocaleCompare(keyword,"file") == 0) { if (depth > MagickMaxRecursionDepth) (void) ThrowMagickException(exception,GetMagickModule(), ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token); else { char path[MagickPathExtent], *file_xml; *path='\0'; GetPathComponent(filename,HeadPath,path); if (*path != '\0') (void) ConcatenateMagickString(path,DirectorySeparator, MagickPathExtent); if (*token == *DirectorySeparator) (void) CopyMagickString(path,token,MagickPathExtent); else (void) ConcatenateMagickString(path,token,MagickPathExtent); file_xml=FileToXML(path,~0UL); if (file_xml != (char *) NULL) { status&=LoadLocaleCache(cache,file_xml,path,locale, depth+1,exception); file_xml=DestroyString(file_xml); } } } } continue; } if (LocaleCompare(keyword,"<locale") == 0) { /* Locale element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); } continue; } if (LocaleCompare(keyword,"</locale>") == 0) { ChopLocaleComponents(tag,1); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (LocaleCompare(keyword,"<localemap>") == 0) continue; if (LocaleCompare(keyword,"</localemap>") == 0) continue; if (LocaleCompare(keyword,"<message") == 0) { /* Message element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"name") == 0) { (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); } } for (p=(char *) q; (*q != '<') && (*q != '\0'); q++) ; while (isspace((int) ((unsigned char) *p)) != 0) p++; q--; while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p)) q--; (void) CopyMagickString(message,p,MagickMin((size_t) (q-p+2), MagickLocaleExtent)); locale_info=(LocaleInfo *) AcquireCriticalMemory(sizeof(*locale_info)); (void) memset(locale_info,0,sizeof(*locale_info)); locale_info->path=ConstantString(filename); locale_info->tag=ConstantString(tag); locale_info->message=ConstantString(message); locale_info->signature=MagickCoreSignature; status=AddValueToSplayTree(cache,locale_info->tag,locale_info); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", locale_info->tag); (void) ConcatenateMagickString(tag,message,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"\n",MagickLocaleExtent); q++; continue; } if (LocaleCompare(keyword,"</message>") == 0) { ChopLocaleComponents(tag,2); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (*keyword == '<') { /* Subpath element. */ if (*(keyword+1) == '?') continue; if (*(keyword+1) == '/') { ChopLocaleComponents(tag,1); if (*tag != '\0') (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } token[strlen(token)-1]='\0'; (void) CopyMagickString(token,token+1,MagickLocaleExtent); (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } GetNextToken(q,(const char **) NULL,extent,token); if (*token != '=') continue; } token=(char *) RelinquishMagickMemory(token); (void) SetFatalErrorHandler(fatal_handler); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % LocaleCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The format of the LocaleCompare method is: % % int LocaleCompare(const char *p,const char *q) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % */ MagickExport int LocaleCompare(const char *p,const char *q) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRCASECMP) return(strcasecmp(p,q)); #else { register int c, d; for ( ; ; ) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if ((c == 0) || (AsciiMap[c] != AsciiMap[d])) break; p++; q++; } return(AsciiMap[c]-(int) AsciiMap[d]); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLower() transforms all of the characters in the supplied % null-terminated string, changing all uppercase letters to lowercase. % % The format of the LocaleLower method is: % % void LocaleLower(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to lower-case Locale. % */ MagickExport void LocaleLower(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleLowercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLowercase() convert to lowercase. % % The format of the LocaleLowercase method is: % % void LocaleLowercase(const int c) % % A description of each parameter follows: % % o If c is a uppercase letter, return its lowercase equivalent. % */ MagickExport int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l(c,c_locale)); #endif return(tolower(c)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e N C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleNCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % % LocaleNCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The LocaleNCompare method makes the same comparison as LocaleCompare but % looks at a maximum of n bytes. Bytes following a null byte are not % compared. % % The format of the LocaleNCompare method is: % % int LocaleNCompare(const char *p,const char *q,const size_t n) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % % o length: the number of characters to compare in strings p and q. % */ MagickExport int LocaleNCompare(const char *p,const char *q,const size_t length) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRNCASECMP) return(strncasecmp(p,q,length)); #else { register int c, d; register size_t i; for (i=length; i != 0; i--) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if (AsciiMap[c] != AsciiMap[d]) return(AsciiMap[c]-(int) AsciiMap[d]); if (c == 0) return(0); p++; q++; } return(0); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUpper() transforms all of the characters in the supplied % null-terminated string, changing all lowercase letters to uppercase. % % The format of the LocaleUpper method is: % % void LocaleUpper(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to upper-case Locale. % */ MagickExport void LocaleUpper(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleUppercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUppercase() convert to uppercase. % % The format of the LocaleUppercase method is: % % void LocaleUppercase(const int c) % % A description of each parameter follows: % % o If c is a lowercase letter, return its uppercase equivalent. % */ MagickExport int LocaleUppercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l(c,c_locale)); #endif return(toupper(c)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentGenesis() instantiates the locale component. % % The format of the LocaleComponentGenesis method is: % % MagickBooleanType LocaleComponentGenesis(void) % */ MagickPrivate MagickBooleanType LocaleComponentGenesis(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) locale_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentTerminus() destroys the locale component. % % The format of the LocaleComponentTerminus method is: % % LocaleComponentTerminus(void) % */ MagickPrivate void LocaleComponentTerminus(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache != (SplayTreeInfo *) NULL) locale_cache=DestroySplayTree(locale_cache); #if defined(MAGICKCORE_LOCALE_SUPPORT) DestroyCLocale(); #endif UnlockSemaphoreInfo(locale_semaphore); RelinquishSemaphoreInfo(&locale_semaphore); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_766_0
crossvul-cpp_data_bad_2861_1
/* radare - LGPL - Copyright 2007-2017 - pancake */ #include <r_flag.h> #include <r_util.h> #include <r_cons.h> #include <stdio.h> R_LIB_VERSION(r_flag); #define ISNULLSTR(x) (!(x) || !*(x)) #define IS_IN_SPACE(f, i) ((f)->space_idx != -1 && (i)->space != (f)->space_idx) static const char *str_callback(RNum *user, ut64 off, int *ok) { const RList *list; RFlag *f = (RFlag*)user; RFlagItem *item; if (ok) { *ok = 0; } if (f) { list = r_flag_get_list (f, off); item = r_list_get_top (list); if (item) { if (ok) { *ok = true; } return item->name; } } return NULL; } static void flag_free_kv(HtKv *kv) { free (kv->key); //we do not free kv->value since there is a reference in other list free (kv); } static void flag_skiplist_free(void *data) { RFlagsAtOffset *item = (RFlagsAtOffset *)data; r_list_free (item->flags); free (data); } static int flag_skiplist_cmp(const void *va, const void *vb) { const RFlagsAtOffset *a = (RFlagsAtOffset *)va, *b = (RFlagsAtOffset *)vb; if (a->off == b->off) { return 0; } return a->off < b->off ? -1 : 1; } static ut64 num_callback(RNum *user, const char *name, int *ok) { RFlag *f = (RFlag*)user; RFlagItem *item; if (ok) { *ok = 0; } item = ht_find (f->ht_name, name, NULL); if (item) { // NOTE: to avoid warning infinite loop here we avoid recursivity if (item->alias) { return 0LL; } if (ok) { *ok = 1; } return item->offset; } return 0LL; } /* return the list of flag at the nearest position. dir == -1 -> result <= off dir == 0 -> result == off dir == 1 -> result >= off*/ static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { RFlagsAtOffset *flags = NULL; RFlagsAtOffset key; key.off = off; if (dir >= 0) { flags = r_skiplist_get_geq (f->by_off, &key); } else { flags = r_skiplist_get_leq (f->by_off, &key); } if (dir == 0 && flags && flags->off != off) { return NULL; } return flags; } static void remove_offsetmap(RFlag *f, RFlagItem *item) { RFlagsAtOffset *flags = r_flag_get_nearest_list (f, item->offset, 0); if (flags) { r_list_delete_data (flags->flags, item); if (r_list_empty (flags->flags)) { r_skiplist_delete (f->by_off, flags); } } } static int set_name(RFlagItem *item, const char *name) { if (item->name != item->realname) { free (item->name); } item->name = strdup (name); if (!item->name) { return false; } r_str_chop (item->name); r_name_filter (item->name, 0); // TODO: name_filter should be chopping already free (item->realname); item->realname = item->name; return true; } R_API RFlag * r_flag_new() { int i; RFlag *f = R_NEW0 (RFlag); if (!f) return NULL; f->num = r_num_new (&num_callback, &str_callback, f); if (!f->num) { r_flag_free (f); return NULL; } f->base = 0; f->cb_printf = (PrintfCallback)printf; #if R_FLAG_ZONE_USE_SDB f->zones = sdb_new0 (); #else f->zones = NULL; #endif f->flags = r_list_new (); if (!f->flags) { r_flag_free (f); return NULL; } f->flags->free = (RListFree) r_flag_item_free; f->space_idx = -1; f->spacestack = r_list_newf (NULL); if (!f->spacestack) { r_flag_free (f); return NULL; } f->ht_name = ht_new (NULL, flag_free_kv, NULL); f->by_off = r_skiplist_new (flag_skiplist_free, flag_skiplist_cmp); #if R_FLAG_ZONE_USE_SDB sdb_free (f->zones); #else r_list_free (f->zones); #endif for (i = 0; i < R_FLAG_SPACES_MAX; i++) { f->spaces[i] = NULL; } return f; } R_API void r_flag_item_free(RFlagItem *item) { if (item) { free (item->color); free (item->comment); free (item->alias); /* release only one of the two pointers if they are the same */ if (item->name != item->realname) { free (item->name); } free (item->realname); free (item); } } R_API RFlag *r_flag_free(RFlag *f) { int i; for (i = 0; i < R_FLAG_SPACES_MAX; i++) { free (f->spaces[i]); } r_skiplist_free (f->by_off); ht_free (f->ht_name); r_list_free (f->flags); r_list_free (f->spacestack); r_num_free (f->num); free (f); return NULL; } /* print with r_cons the flag items in the flag f, given as a parameter */ R_API void r_flag_list(RFlag *f, int rad, const char *pfx) { bool in_range = false; ut64 range_from = UT64_MAX; ut64 range_to = UT64_MAX; int fs = -1; RListIter *iter; RFlagItem *flag; if (rad == 'i') { char *sp, *arg = strdup (pfx + 1); sp = strchr (arg, ' '); if (sp) { *sp++ = 0; range_from = r_num_math (f->num, arg); range_to = r_num_math (f->num, sp); } else { const int bsize = 4096; range_from = r_num_math (f->num, arg); range_to = range_from + bsize; } in_range = true; free (arg); rad = pfx[0]; pfx = NULL; } if (pfx && !*pfx) { pfx = NULL; } switch (rad) { case 'j': { int first = 1; f->cb_printf ("["); r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } f->cb_printf ("%s{\"name\":\"%s\",\"size\":%"PFMT64d",", first?"":",", flag->name, flag->size); if (flag->alias) { f->cb_printf ("\"alias\":\"%s\"", flag->alias); } else { f->cb_printf ("\"offset\":%"PFMT64d, flag->offset); } if (flag->comment) f->cb_printf (",\"comment\":\"}"); else f->cb_printf ("}"); first = 0; } f->cb_printf ("]\n"); } break; case 1: case '*': r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } if (fs == -1 || flag->space != fs) { const char *flagspace; fs = flag->space; flagspace = r_flag_space_get_i (f, fs); if (!flagspace || !*flagspace) flagspace = "*"; f->cb_printf ("fs %s\n", flagspace); } if (flag->alias) { f->cb_printf ("fa %s %s\n", flag->name, flag->alias); if (flag->comment && *flag->comment) f->cb_printf ("\"fC %s %s\"\n", flag->name, flag->comment); } else { f->cb_printf ("f %s %"PFMT64d" 0x%08"PFMT64x"%s%s %s\n", flag->name, flag->size, flag->offset, pfx?"+":"", pfx?pfx:"", flag->comment? flag->comment:""); } } break; case 'n': // show original name r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } if (flag->alias) { f->cb_printf ("%s %"PFMT64d" %s\n", flag->alias, flag->size, flag->realname); } else { f->cb_printf ("0x%08"PFMT64x" %"PFMT64d" %s\n", flag->offset, flag->size, flag->realname); } } break; default: r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) { continue; } if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { continue; } if (flag->alias) { f->cb_printf ("%s %"PFMT64d" %s\n", flag->alias, flag->size, flag->name); } else { f->cb_printf ("0x%08"PFMT64x" %"PFMT64d" %s\n", flag->offset, flag->size, flag->name); } } break; } } static RFlagItem *evalFlag(RFlag *f, RFlagItem *item) { if (item && item->alias) { item->offset = r_num_math (f->num, item->alias); } return item; } /* return true if flag.* exist at offset. Otherwise, false is returned. * For example (f, "sym", 3, 0x1000)*/ R_API bool r_flag_exist_at(RFlag *f, const char *flag_prefix, ut16 fp_size, ut64 off) { RListIter *iter = NULL; RFlagItem *item = NULL; if (!f) { return false; } const RList *list = r_flag_get_list (f, off); if (!list) { return false; } r_list_foreach (list, iter, item) { if (item->name && !strncmp (item->name, flag_prefix, fp_size)) { return true; } } return false; } /* return the flag item with name "name" in the RFlag "f", if it exists. * Otherwise, NULL is returned. */ R_API RFlagItem *r_flag_get(RFlag *f, const char *name) { RFlagItem *r; if (!f) { return NULL; } r = ht_find (f->ht_name, name, NULL); return evalFlag (f, r); } /* return the first flag item that can be found at offset "off", or NULL otherwise */ R_API RFlagItem *r_flag_get_i(RFlag *f, ut64 off) { const RList *list; if (!f) { return NULL; } list = r_flag_get_list (f, off); return list ? evalFlag (f, r_list_get_top (list)) : NULL; } /* return the first flag item at offset "off" that doesn't start with "loc.", * "fcn.", "section." or NULL if such a flag doesn't exist. * * XXX: this function is buggy and it's not really clear what's the purpose */ R_API RFlagItem *r_flag_get_i2(RFlag *f, ut64 off) { RFlagItem *oitem = NULL, *item = NULL; RListIter *iter; const RList *list = r_flag_get_list (f, off); if (!list) { return NULL; } r_list_foreach (list, iter, item) { if (!item->name) { continue; } /* catch sym. first */ if (!strncmp (item->name, "loc.", 4)) { continue; } if (!strncmp (item->name, "fcn.", 4)) { continue; } if (!strncmp (item->name, "section.", 8)) { continue; } if (!strncmp (item->name, "section_end.", 12)) { continue; } if (r_str_nlen (item->name, 5) > 4 && item->name[3] == '.') { oitem = item; break; } oitem = item; if (strlen (item->name) < 5 || item->name[3]!='.') continue; oitem = item; } return evalFlag (f, oitem); } static bool isFunctionFlag(const char *n) { return (!strncmp (n, "sym.func.", 9) || !strncmp (n, "method.", 7) || !strncmp (n, "sym.", 7) || !strncmp (n, "func.", 5) || !strncmp (n, "fcn.0", 5)); } /* returns the last flag item defined before or at the given offset. * NULL is returned if such a item is not found. */ R_API RFlagItem *r_flag_get_at(RFlag *f, ut64 off, bool closest) { RFlagItem *item, *nice = NULL; RListIter *iter; const RFlagsAtOffset *flags_at = r_flag_get_nearest_list (f, off, -1); if (!flags_at) { return NULL; } if (flags_at->off == off) { r_list_foreach (flags_at->flags, iter, item) { if (f->space_idx != -1 && item->space != f->space_idx) { continue; } if (nice) { if (isFunctionFlag (nice->name)) { nice = item; } } else { nice = item; } } return nice; } if (!closest) { return NULL; } while (!nice && flags_at) { r_list_foreach (flags_at->flags, iter, item) { if (f->space_strict && IS_IN_SPACE (f, item)) { continue; } if (item->offset == off) { eprintf ("XXX Should never happend\n"); return evalFlag (f, item); } nice = item; break; } if (flags_at->off) { flags_at = r_flag_get_nearest_list (f, flags_at->off - 1, -1); } else { flags_at = NULL; } } return evalFlag (f, nice); } /* return the list of flag items that are associated with a given offset */ R_API const RList* /*<RFlagItem*>*/ r_flag_get_list(RFlag *f, ut64 off) { const RFlagsAtOffset *item = r_flag_get_nearest_list (f, off, 0); return item ? item->flags : NULL; } R_API char *r_flag_get_liststr(RFlag *f, ut64 off) { RFlagItem *fi; RListIter *iter; const RList *list = r_flag_get_list (f, off); char *p = NULL; r_list_foreach (list, iter, fi) { p = r_str_appendf (p, "%s%s", fi->realname, iter->n ? "," : ":"); } return p; } R_API RFlagItem *r_flag_set_next(RFlag *f, const char *name, ut64 off, ut32 size) { if (!r_flag_get (f, name)) { return r_flag_set (f, name, off, size); } int i, newNameSize = strlen (name); char *newName = malloc (newNameSize + 16); strcpy (newName, name); for (i = 0; ; i++) { snprintf (newName + newNameSize, 15, ".%d", i); if (!r_flag_get (f, newName)) { RFlagItem *fi = r_flag_set (f, newName, off, size); free (newName); return fi; } } return NULL; } /* create or modify an existing flag item with the given name and parameters. * The realname of the item will be the same as the name. * NULL is returned in case of any errors during the process. */ R_API RFlagItem *r_flag_set(RFlag *f, const char *name, ut64 off, ut32 size) { RFlagItem *item = NULL; RList *list; /* contract fail */ if (!name || !*name) { return NULL; } item = r_flag_get (f, name); if (item) { if (item->offset == off) { item->size = size; return item; } remove_offsetmap (f, item); } else { item = R_NEW0 (RFlagItem); if (!item) { return NULL; } if (!set_name (item, name)) { eprintf ("Invalid flag name '%s'.\n", name); r_flag_item_free (item); return NULL; } //item share ownership prone to uaf, that is why only //f->flags has set up free pointer ht_insert (f->ht_name, item->name, item); r_list_append (f->flags, item); } item->space = f->space_idx; item->offset = off + f->base; item->size = size; list = (RList *)r_flag_get_list (f, off); if (!list) { RFlagsAtOffset *flagsAtOffset = R_NEW (RFlagsAtOffset); list = r_list_new (); flagsAtOffset->flags = list; flagsAtOffset->off = off; // CID 1378268: Resource leaks (RESOURCE_LEAK) // Ignoring storage allocated by "r_skiplist_insert(f->by_off, flagsAtOffset)" leaks it. r_skiplist_insert (f->by_off, flagsAtOffset); } r_list_append (list, item); return item; } /* add/replace/remove the alias of a flag item */ R_API void r_flag_item_set_alias(RFlagItem *item, const char *alias) { if (item) { free (item->alias); item->alias = ISNULLSTR (alias)? NULL: strdup (alias); } } /* add/replace/remove the comment of a flag item */ R_API void r_flag_item_set_comment(RFlagItem *item, const char *comment) { if (item) { free (item->comment); item->comment = ISNULLSTR (comment) ? NULL : strdup (comment); } } /* add/replace/remove the realname of a flag item */ R_API void r_flag_item_set_realname(RFlagItem *item, const char *realname) { if (item) { if (item->name != item->realname) { free (item->realname); } item->realname = ISNULLSTR (realname) ? NULL : strdup (realname); } } /* change the name of a flag item, if the new name is available. * true is returned if everything works well, false otherwise */ R_API int r_flag_rename(RFlag *f, RFlagItem *item, const char *name) { if (!f || !item || !name || !*name) { return false; } #if 0 ut64 off = item->offset; int size = item->size; r_flag_unset (f, item); r_flag_set (f, name, off, size); return true; #else ht_delete (f->ht_name, item->name); if (!set_name (item, name)) { return false; } ht_insert (f->ht_name, item->name, item); #endif return true; } /* unset the given flag item. * returns true if the item is successfully unset, false otherwise. * * NOTE: the item is freed. */ R_API int r_flag_unset(RFlag *f, RFlagItem *item) { remove_offsetmap (f, item); ht_delete (f->ht_name, item->name); r_list_delete_data (f->flags, item); return true; } /* unset the first flag item found at offset off. * return true if such a flag is found and unset, false otherwise. */ R_API int r_flag_unset_off(RFlag *f, ut64 off) { RFlagItem *item = r_flag_get_i (f, off); if (item && r_flag_unset (f, item)) { return true; } return false; } /* unset all the flag items that satisfy the given glob. * return the number of unset items. */ R_API int r_flag_unset_glob(RFlag *f, const char *glob) { RListIter it, *iter; RFlagItem *flag; int n = 0; r_list_foreach (f->flags, iter, flag) { if (IS_IN_SPACE (f, flag)) continue; if (!glob || r_str_glob (flag->name, glob)) { it.n = iter->n; r_flag_unset (f, flag); iter = &it; n++; } } return n; } /* unset the flag item with the given name. * returns true if the item is found and unset, false otherwise. */ R_API int r_flag_unset_name(RFlag *f, const char *name) { RFlagItem *item = ht_find (f->ht_name, name, NULL); return item && r_flag_unset (f, item); } /* unset all flag items in the RFlag f */ R_API void r_flag_unset_all(RFlag *f) { f->space_idx = -1; r_list_free (f->flags); f->flags = r_list_newf ((RListFree)r_flag_item_free); if (!f->flags) { return; } ht_free (f->ht_name); //don't set free since f->flags will free up items when needed avoiding uaf f->ht_name = ht_new (NULL, flag_free_kv, NULL); r_skiplist_purge (f->by_off); r_flag_space_unset (f, NULL); } R_API int r_flag_relocate(RFlag *f, ut64 off, ut64 off_mask, ut64 to) { ut64 neg_mask = ~(off_mask); RFlagItem *item; RListIter *iter; int n = 0; r_list_foreach (f->flags, iter, item) { ut64 fn = item->offset & neg_mask; ut64 on = off & neg_mask; if (fn == on) { ut64 fm = item->offset & off_mask; ut64 om = to & off_mask; item->offset = (to&neg_mask) + fm + om; n++; } } return n; } R_API int r_flag_move(RFlag *f, ut64 at, ut64 to) { RFlagItem *item = r_flag_get_i (f, at); if (item) { r_flag_set (f, item->name, to, item->size); return true; } return false; } #ifdef MYTEST int main () { RFlagItem *i; RFlag *f = r_flag_new (); r_flag_set (f, "rip", 0xfff333999000LL, 1); r_flag_set (f, "rip", 0xfff333999002LL, 1); r_flag_unset (f, "rip", NULL); r_flag_set (f, "rip", 3, 4); r_flag_set (f, "rip", 4, 4); r_flag_set (f, "corwp", 300, 4); r_flag_set (f, "barp", 300, 4); r_flag_set (f, "rip", 3, 4); r_flag_set (f, "rip", 4, 4); i = r_flag_get (f, "rip"); if (i) printf ("nRIP: %p %llx\n", i, i->offset); else printf ("nRIP: null\n"); i = r_flag_get_i (f, 0xfff333999000LL); if (i) printf ("iRIP: %p %llx\n", i, i->offset); else printf ("iRIP: null\n"); } #endif R_API const char *r_flag_color(RFlag *f, RFlagItem *it, const char *color) { if (!f || !it) return NULL; if (!color) return it->color; free (it->color); it->color = *color ? strdup (color) : NULL; return it->color; } // BIND R_API int r_flag_bind(RFlag *f, RFlagBind *fb) { fb->f = f; fb->exist_at = r_flag_exist_at; fb->get = r_flag_get; fb->get_at = r_flag_get_at; fb->set = r_flag_set; fb->set_fs = r_flag_space_set; return 0; } R_API int r_flag_count(RFlag *f, const char *glob) { int count = 0; RFlagItem *flag; RListIter *iter; r_list_foreach (f->flags, iter, flag) { if (r_str_glob (flag->name, glob)) count ++; } return count; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2861_1
crossvul-cpp_data_good_2588_1
/* * hmi.c -- Midi Wavetable Processing library * * Copyright (C) WildMIDI Developers 2001-2016 * * This file is part of WildMIDI. * * WildMIDI is free software: you can redistribute and/or modify the player * under the terms of the GNU General Public License and you can redistribute * and/or modify the library under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either version 3 of * the licenses, or(at your option) any later version. * * WildMIDI 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 and * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License and the * GNU Lesser General Public License along with WildMIDI. If not, see * <http://www.gnu.org/licenses/>. */ #include "config.h" #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "common.h" #include "wm_error.h" #include "wildmidi_lib.h" #include "internal_midi.h" #include "reverb.h" #include "f_hmi.h" /* Turns hmp file data into an event stream */ struct _mdi * _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { uint32_t hmi_tmp = 0; uint8_t *hmi_base = hmi_data; uint32_t data_siz; uint16_t hmi_bpm = 0; uint16_t hmi_division = 0; uint32_t hmi_track_cnt = 0; uint32_t *hmi_track_offset = NULL; uint32_t i = 0; uint32_t j = 0; uint8_t *hmi_addr = NULL; uint32_t *hmi_track_header_length = NULL; struct _mdi *hmi_mdi = NULL; uint32_t tempo_f = 5000000.0; uint32_t *hmi_track_end = NULL; uint8_t hmi_tracks_ended = 0; uint8_t *hmi_running_event = NULL; uint32_t setup_ret = 0; uint32_t *hmi_delta = NULL; uint32_t smallest_delta = 0; uint32_t subtract_delta = 0; uint32_t sample_count = 0; float sample_count_f = 0; float sample_remainder = 0; float samples_per_delta_f = 0.0; struct _note { uint32_t length; uint8_t channel; } *note; if (memcmp(hmi_data, "HMI-MIDISONG061595", 18)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); return NULL; } //FIXME: Unsure if this is correct but it seems to be the only offset that plays the files at what appears to be the right speed. hmi_bpm = hmi_data[212]; hmi_division = 60; hmi_track_cnt = hmi_data[228]; hmi_mdi = _WM_initMDI(); _WM_midi_setup_divisions(hmi_mdi, hmi_division); if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / hmi_bpm) + 0.5f; } else { tempo_f = (float) (60000000 / hmi_bpm); } samples_per_delta_f = _WM_GetSamplesPerTick(hmi_division, (uint32_t)tempo_f); _WM_midi_setup_tempo(hmi_mdi, (uint32_t)tempo_f); hmi_track_offset = (uint32_t *)malloc(sizeof(uint32_t) * hmi_track_cnt); hmi_track_header_length = malloc(sizeof(uint32_t) * hmi_track_cnt); hmi_track_end = malloc(sizeof(uint32_t) * hmi_track_cnt); hmi_delta = malloc(sizeof(uint32_t) * hmi_track_cnt); note = malloc(sizeof(struct _note) * 128 * hmi_track_cnt); hmi_running_event = malloc(sizeof(uint8_t) * 128 * hmi_track_cnt); hmi_data += 370; smallest_delta = 0xffffffff; if (hmi_size < (370 + (hmi_track_cnt * 17))) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0); goto _hmi_end; } hmi_track_offset[0] = *hmi_data; // To keep Xcode happy for (i = 0; i < hmi_track_cnt; i++) { hmi_track_offset[i] = *hmi_data++; hmi_track_offset[i] += (*hmi_data++ << 8); hmi_track_offset[i] += (*hmi_data++ << 16); hmi_track_offset[i] += (*hmi_data++ << 24); if (hmi_size < (hmi_track_offset[i] + 0x5a + 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0); goto _hmi_end; } hmi_addr = hmi_base + hmi_track_offset[i]; if (memcmp(hmi_addr, "HMI-MIDITRACK", 13)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); goto _hmi_end; } hmi_track_header_length[i] = hmi_addr[0x57]; hmi_track_header_length[i] += (hmi_addr[0x58] << 8); hmi_track_header_length[i] += (hmi_addr[0x59] << 16); hmi_track_header_length[i] += (hmi_addr[0x5a] << 24); hmi_addr += hmi_track_header_length[i]; hmi_track_offset[i] += hmi_track_header_length[i]; // Get tracks initial delta and set its samples_till_next; hmi_delta[i] = 0; if (*hmi_addr > 0x7f) { do { hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f); hmi_addr++; hmi_track_offset[i]++; } while (*hmi_addr > 0x7f); } hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f); hmi_track_offset[i]++; hmi_addr++; // Find smallest delta to work with if (hmi_delta[i] < smallest_delta) { smallest_delta = hmi_delta[i]; } hmi_track_end[i] = 0; hmi_running_event[i] = 0; for (j = 0; j < 128; j++) { hmi_tmp = (128 * i) + j; note[hmi_tmp].length = 0; note[hmi_tmp].channel = 0; } } subtract_delta = smallest_delta; sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count; hmi_mdi->extra_info.approx_total_samples += sample_count; while (hmi_tracks_ended < hmi_track_cnt) { smallest_delta = 0; for (i = 0; i < hmi_track_cnt; i++) { if (hmi_track_end[i]) continue; // first check to see if any active notes need turning off. for (j = 0; j < 128; j++) { hmi_tmp = (128 * i) + j; if (note[hmi_tmp].length) { note[hmi_tmp].length -= subtract_delta; if (note[hmi_tmp].length) { if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) { smallest_delta = note[hmi_tmp].length; } } else { _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); } } } if (hmi_delta[i]) { hmi_delta[i] -= subtract_delta; if (hmi_delta[i]) { if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) { smallest_delta = hmi_delta[i]; } continue; } } do { hmi_data = hmi_base + hmi_track_offset[i]; hmi_delta[i] = 0; if (hmi_track_offset[i] >= hmi_size) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0); goto _hmi_end; } data_siz = hmi_size - hmi_track_offset[i]; if (hmi_data[0] == 0xfe) { // HMI only event of some sort. if (hmi_data[1] == 0x10) { hmi_tmp = (hmi_data[4] + 5); hmi_data += hmi_tmp; hmi_track_offset[i] += hmi_tmp; hmi_tmp += 4; } else if (hmi_data[1] == 0x15) { hmi_data += 4; hmi_track_offset[i] += 4; hmi_tmp = 8; } else { hmi_tmp = 4; } hmi_data += 4; hmi_track_offset[i] += 4; if (hmi_tmp > data_siz) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0); goto _hmi_end; } data_siz -= hmi_tmp; } else { if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,data_siz,hmi_running_event[i])) == 0) { goto _hmi_end; } if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) { hmi_track_end[i] = 1; hmi_tracks_ended++; for(j = 0; j < 128; j++) { hmi_tmp = (128 * i) + j; if (note[hmi_tmp].length) { _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); note[hmi_tmp].length = 0; } } goto _hmi_next_track; } // Running event // 0xff does not alter running event if ((*hmi_data == 0xF0) || (*hmi_data == 0xF7)) { // Sysex resets running event data hmi_running_event[i] = 0; } else if (*hmi_data < 0xF0) { // MIDI events 0x80 to 0xEF set running event if (*hmi_data >= 0x80) { hmi_running_event[i] = *hmi_data; } } if ((hmi_running_event[i] & 0xf0) == 0x90) { // note on has extra data to specify how long the note is. if (*hmi_data > 127) { hmi_tmp = hmi_data[1]; } else { hmi_tmp = *hmi_data; } hmi_tmp += (i * 128); note[hmi_tmp].channel = hmi_running_event[i] & 0xf; hmi_data += setup_ret; hmi_track_offset[i] += setup_ret; data_siz -= setup_ret; note[hmi_tmp].length = 0; if (data_siz && *hmi_data > 0x7f) { do { if (!data_siz) break; note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); hmi_data++; data_siz--; hmi_track_offset[i]++; } while (*hmi_data > 0x7F); } if (!data_siz) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0); goto _hmi_end; } note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); hmi_data++; data_siz--; hmi_track_offset[i]++; if (note[hmi_tmp].length) { if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) { smallest_delta = note[hmi_tmp].length; } } else { _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); } } else { hmi_data += setup_ret; hmi_track_offset[i] += setup_ret; data_siz -= setup_ret; } } // get track delta // hmi_delta[i] = 0; // set at start of loop if (data_siz && *hmi_data > 0x7f) { do { if (!data_siz) break; hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); hmi_data++; data_siz--; hmi_track_offset[i]++; } while (*hmi_data > 0x7F); } if (!data_siz) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0); goto _hmi_end; } hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); hmi_data++; data_siz--; hmi_track_offset[i]++; } while (!hmi_delta[i]); if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) { smallest_delta = hmi_delta[i]; } _hmi_next_track: hmi_tmp = 0; UNUSED(hmi_tmp); } // convert smallest delta to samples till next subtract_delta = smallest_delta; sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count; hmi_mdi->extra_info.approx_total_samples += sample_count; } if ((hmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _hmi_end; } hmi_mdi->extra_info.current_sample = 0; hmi_mdi->current_event = &hmi_mdi->events[0]; hmi_mdi->samples_to_mix = 0; hmi_mdi->note = NULL; _WM_ResetToStart(hmi_mdi); _hmi_end: free(hmi_track_offset); free(hmi_track_header_length); free(hmi_track_end); free(hmi_delta); free(note); free(hmi_running_event); if (hmi_mdi->reverb) return (hmi_mdi); _WM_freeMDI(hmi_mdi); return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2588_1
crossvul-cpp_data_good_1016_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % X X W W DDDD % % X X W W D D % % X W W D D % % X X W W W D D % % X X W W DDDD % % % % % % Read/Write X Windows System Window Dump 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-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-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/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/string_.h" #include "MagickCore/module.h" #if defined(MAGICKCORE_X11_DELEGATE) #include "MagickCore/xwindow-private.h" #if !defined(vms) #include <X11/XWDFile.h> #else #include "XWDFile.h" #endif #endif /* Forward declarations. */ #if defined(MAGICKCORE_X11_DELEGATE) static MagickBooleanType WriteXWDImage(const ImageInfo *,Image *,ExceptionInfo *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s X W D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsXWD() returns MagickTrue if the image format type, identified by the % magick string, is XWD. % % The format of the IsXWD method is: % % MagickBooleanType IsXWD(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 IsXWD(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick+1,"\000\000",2) == 0) { if (memcmp(magick+4,"\007\000\000",3) == 0) return(MagickTrue); if (memcmp(magick+5,"\000\000\007",3) == 0) return(MagickTrue); } return(MagickFalse); } #if defined(MAGICKCORE_X11_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXWDImage() reads an X Window System window dump 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 ReadXWDImage method is: % % Image *ReadXWDImage(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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* 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 in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((MagickSizeType) header.xoffset >= GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: { if (header.bits_per_pixel != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case StaticColor: case PseudoColor: { if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) || (header.colormap_entries == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case TrueColor: case DirectColor: { if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) && (header.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: { if (header.pixmap_depth != 1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; } case XYPixmap: case ZPixmap: { if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.bitmap_pad) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_unit) { case 8: case 16: case 32: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.byte_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.bitmap_bit_order) { case LSBFirst: case MSBFirst: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); length=(size_t) (header.header_size-sz_XWDheader); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask,exception); SetPixelRed(image,ScaleShortToQuantum( colors[(ssize_t) index].red),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask,exception); SetPixelGreen(image,ScaleShortToQuantum( colors[(ssize_t) index].green),q); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask,exception); SetPixelBlue(image,ScaleShortToQuantum( colors[(ssize_t) index].blue),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color), q); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleShortToQuantum( colors[i].red); image->colormap[i].green=(MagickRealType) ScaleShortToQuantum( colors[i].green); image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum( colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=(Quantum) ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y),exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterXWDImage() adds properties for the XWD 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 RegisterXWDImage method is: % % size_t RegisterXWDImage(void) % */ ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterXWDImage() removes format registrations made by the % XWD module from the list of supported formats. % % The format of the UnregisterXWDImage method is: % % UnregisterXWDImage(void) % */ ModuleExport void UnregisterXWDImage(void) { (void) UnregisterMagickInfo("XWD"); } #if defined(MAGICKCORE_X11_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteXWDImage() writes an image to a file in X window dump % rasterfile format. % % The format of the WriteXWDImage method is: % % MagickBooleanType WriteXWDImage(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 WriteXWDImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *value; MagickBooleanType status; register const Quantum *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, bytes_per_line, length, scanline_pad; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; XWDFileHeader xwd_info; /* 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); if ((image->columns != (CARD32) image->columns) || (image->rows != (CARD32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageType(image,TrueColorType,exception); (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Initialize XWD file header. */ (void) memset(&xwd_info,0,sizeof(xwd_info)); xwd_info.header_size=(CARD32) sz_XWDheader; value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) xwd_info.header_size+=(CARD32) strlen(value); xwd_info.header_size++; xwd_info.file_version=(CARD32) XWD_FILE_VERSION; xwd_info.pixmap_format=(CARD32) ZPixmap; xwd_info.pixmap_depth=(CARD32) (image->storage_class == DirectClass ? 24 : 8); xwd_info.pixmap_width=(CARD32) image->columns; xwd_info.pixmap_height=(CARD32) image->rows; xwd_info.xoffset=(CARD32) 0; xwd_info.byte_order=(CARD32) MSBFirst; xwd_info.bitmap_unit=(CARD32) (image->storage_class == DirectClass ? 32 : 8); xwd_info.bitmap_bit_order=(CARD32) MSBFirst; xwd_info.bitmap_pad=(CARD32) (image->storage_class == DirectClass ? 32 : 8); bits_per_pixel=(size_t) (image->storage_class == DirectClass ? 24 : 8); xwd_info.bits_per_pixel=(CARD32) bits_per_pixel; bytes_per_line=(CARD32) ((((xwd_info.bits_per_pixel* xwd_info.pixmap_width)+((xwd_info.bitmap_pad)-1))/ (xwd_info.bitmap_pad))*((xwd_info.bitmap_pad) >> 3)); xwd_info.bytes_per_line=(CARD32) bytes_per_line; xwd_info.visual_class=(CARD32) (image->storage_class == DirectClass ? DirectColor : PseudoColor); xwd_info.red_mask=(CARD32) (image->storage_class == DirectClass ? 0xff0000 : 0); xwd_info.green_mask=(CARD32) (image->storage_class == DirectClass ? 0xff00 : 0); xwd_info.blue_mask=(CARD32) (image->storage_class == DirectClass ? 0xff : 0); xwd_info.bits_per_rgb=(CARD32) (image->storage_class == DirectClass ? 24 : 8); xwd_info.colormap_entries=(CARD32) (image->storage_class == DirectClass ? 256 : image->colors); xwd_info.ncolors=(unsigned int) (image->storage_class == DirectClass ? 0 : image->colors); xwd_info.window_width=(CARD32) image->columns; xwd_info.window_height=(CARD32) image->rows; xwd_info.window_x=0; xwd_info.window_y=0; xwd_info.window_bdrwidth=(CARD32) 0; /* Write XWD header. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &xwd_info,sizeof(xwd_info)); (void) WriteBlob(image,sz_XWDheader,(unsigned char *) &xwd_info); if (value != (const char *) NULL) (void) WriteBlob(image,strlen(value),(unsigned char *) value); (void) WriteBlob(image,1,(const unsigned char *) "\0"); if (image->storage_class == PseudoClass) { register ssize_t i; XColor *colors; XWDColor color; /* Dump colormap to file. */ (void) memset(&color,0,sizeof(color)); colors=(XColor *) AcquireQuantumMemory((size_t) image->colors, sizeof(*colors)); if (colors == (XColor *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) { colors[i].pixel=(unsigned long) i; colors[i].red=ScaleQuantumToShort(ClampToQuantum( image->colormap[i].red)); colors[i].green=ScaleQuantumToShort(ClampToQuantum( image->colormap[i].green)); colors[i].blue=ScaleQuantumToShort(ClampToQuantum( image->colormap[i].blue)); colors[i].flags=(char) (DoRed | DoGreen | DoBlue); colors[i].pad='\0'; if ((int) (*(char *) &lsb_first) != 0) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } for (i=0; i < (ssize_t) image->colors; i++) { color.pixel=(CARD32) colors[i].pixel; color.red=colors[i].red; color.green=colors[i].green; color.blue=colors[i].blue; color.flags=(CARD8) colors[i].flags; count=WriteBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != (ssize_t) sz_XWDColor) break; } colors=(XColor *) RelinquishMagickMemory(colors); } /* Allocate memory for pixels. */ length=3*bytes_per_line; if (image->storage_class == PseudoClass) length=bytes_per_line; pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pixels,0,length); /* Convert MIFF to XWD raster pixels. */ scanline_pad=(bytes_per_line-((image->columns*bits_per_pixel) >> 3)); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; if (image->storage_class == PseudoClass) { for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } } else for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) *q++='\0'; length=(size_t) (q-pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_1016_0
crossvul-cpp_data_good_5239_2
/** * Test that crafted TGA files don't trigger OOB reads. */ #include "gd.h" #include "gdtest.h" static void check_file(char *basename); static size_t read_test_file(char **buffer, char *basename); int main() { check_file("heap_overflow_1.tga"); check_file("heap_overflow_2.tga"); return gdNumFailures(); } static void check_file(char *basename) { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, basename); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); } static size_t read_test_file(char **buffer, char *basename) { char *filename; FILE *fp; size_t exp_size, act_size; filename = gdTestFilePath2("tga", basename); fp = fopen(filename, "rb"); gdTestAssert(fp != NULL); fseek(fp, 0, SEEK_END); exp_size = ftell(fp); fseek(fp, 0, SEEK_SET); *buffer = malloc(exp_size); gdTestAssert(*buffer != NULL); act_size = fread(*buffer, sizeof(**buffer), exp_size, fp); gdTestAssert(act_size == exp_size); fclose(fp); free(filename); return act_size; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5239_2
crossvul-cpp_data_good_5491_1
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Tier-2 Coding Library * * $Id$ */ #include "jasper/jas_math.h" #include "jasper/jas_malloc.h" #include "jpc_cs.h" #include "jpc_t2cod.h" #include "jpc_math.h" static int jpc_pi_nextlrcp(jpc_pi_t *pi); static int jpc_pi_nextrlcp(jpc_pi_t *pi); static int jpc_pi_nextrpcl(jpc_pi_t *pi); static int jpc_pi_nextpcrl(jpc_pi_t *pi); static int jpc_pi_nextcprl(jpc_pi_t *pi); int jpc_pi_next(jpc_pi_t *pi) { jpc_pchg_t *pchg; int ret; for (;;) { pi->valid = false; if (!pi->pchg) { ++pi->pchgno; pi->compno = 0; pi->rlvlno = 0; pi->prcno = 0; pi->lyrno = 0; pi->prgvolfirst = true; if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno); } else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = &pi->defaultpchg; } else { return 1; } } pchg = pi->pchg; switch (pchg->prgord) { case JPC_COD_LRCPPRG: ret = jpc_pi_nextlrcp(pi); break; case JPC_COD_RLCPPRG: ret = jpc_pi_nextrlcp(pi); break; case JPC_COD_RPCLPRG: ret = jpc_pi_nextrpcl(pi); break; case JPC_COD_PCRLPRG: ret = jpc_pi_nextpcrl(pi); break; case JPC_COD_CPRLPRG: ret = jpc_pi_nextcprl(pi); break; default: ret = -1; break; } if (!ret) { pi->valid = true; ++pi->pktno; return 0; } pi->pchg = 0; } } static int jpc_pi_nextlrcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = false; } for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrlcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { assert(pi->prcno < pi->pirlvl->numprcs); prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextpcrl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextcprl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->prgvolfirst = 0; } for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { pirlvl = pi->picomp->pirlvls; // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - rlvlno - 1))); pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - rlvlno - 1))); } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static void pirlvl_destroy(jpc_pirlvl_t *rlvl) { if (rlvl->prclyrnos) { jas_free(rlvl->prclyrnos); } } static void jpc_picomp_destroy(jpc_picomp_t *picomp) { int rlvlno; jpc_pirlvl_t *pirlvl; if (picomp->pirlvls) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { pirlvl_destroy(pirlvl); } jas_free(picomp->pirlvls); } } void jpc_pi_destroy(jpc_pi_t *pi) { jpc_picomp_t *picomp; int compno; if (pi->picomps) { for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { jpc_picomp_destroy(picomp); } jas_free(pi->picomps); } if (pi->pchglist) { jpc_pchglist_destroy(pi->pchglist); } jas_free(pi); } jpc_pi_t *jpc_pi_create0() { jpc_pi_t *pi; if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) { return 0; } pi->picomps = 0; pi->pchgno = 0; if (!(pi->pchglist = jpc_pchglist_create())) { jas_free(pi); return 0; } return pi; } int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg) { return jpc_pchglist_insert(pi->pchglist, -1, pchg); } jpc_pchglist_t *jpc_pchglist_create() { jpc_pchglist_t *pchglist; if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) { return 0; } pchglist->numpchgs = 0; pchglist->maxpchgs = 0; pchglist->pchgs = 0; return pchglist; } int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg) { int i; int newmaxpchgs; jpc_pchg_t **newpchgs; if (pchgno < 0) { pchgno = pchglist->numpchgs; } if (pchglist->numpchgs >= pchglist->maxpchgs) { newmaxpchgs = pchglist->maxpchgs + 128; if (!(newpchgs = jas_realloc2(pchglist->pchgs, newmaxpchgs, sizeof(jpc_pchg_t *)))) { return -1; } pchglist->maxpchgs = newmaxpchgs; pchglist->pchgs = newpchgs; } for (i = pchglist->numpchgs; i > pchgno; --i) { pchglist->pchgs[i] = pchglist->pchgs[i - 1]; } pchglist->pchgs[pchgno] = pchg; ++pchglist->numpchgs; return 0; } jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno) { int i; jpc_pchg_t *pchg; assert(pchgno < pchglist->numpchgs); pchg = pchglist->pchgs[pchgno]; for (i = pchgno + 1; i < pchglist->numpchgs; ++i) { pchglist->pchgs[i - 1] = pchglist->pchgs[i]; } --pchglist->numpchgs; return pchg; } jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg) { jpc_pchg_t *newpchg; if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) { return 0; } *newpchg = *pchg; return newpchg; } jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist) { jpc_pchglist_t *newpchglist; jpc_pchg_t *newpchg; int pchgno; if (!(newpchglist = jpc_pchglist_create())) { return 0; } for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) || jpc_pchglist_insert(newpchglist, -1, newpchg)) { jpc_pchglist_destroy(newpchglist); return 0; } } return newpchglist; } void jpc_pchglist_destroy(jpc_pchglist_t *pchglist) { int pchgno; if (pchglist->pchgs) { for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { jpc_pchg_destroy(pchglist->pchgs[pchgno]); } jas_free(pchglist->pchgs); } jas_free(pchglist); } void jpc_pchg_destroy(jpc_pchg_t *pchg) { jas_free(pchg); } jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno) { return pchglist->pchgs[pchgno]; } int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist) { return pchglist->numpchgs; } int jpc_pi_init(jpc_pi_t *pi) { int compno; int rlvlno; int prcno; jpc_picomp_t *picomp; jpc_pirlvl_t *pirlvl; int *prclyrno; pi->prgvolfirst = 0; pi->valid = 0; pi->pktno = -1; pi->pchgno = -1; pi->pchg = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { for (prcno = 0, prclyrno = pirlvl->prclyrnos; prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { *prclyrno = 0; } } } return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5491_1
crossvul-cpp_data_good_2644_5
/* $OpenBSD: print-gre.c,v 1.6 2002/10/30 03:04:04 fgsch Exp $ */ /* * Copyright (c) 2002 Jason L. Wright (jason@thought.net) * 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 acknowledgement: * This product includes software developed by Jason L. Wright * 4. 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. */ /* \summary: Generic Routing Encapsulation (GRE) printer */ /* * netdissect printer for GRE - Generic Routing Encapsulation * RFC1701 (GRE), RFC1702 (GRE IPv4), and RFC2637 (Enhanced GRE) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtostr.h" #include "extract.h" #include "ethertype.h" static const char tstr[] = "[|gre]"; #define GRE_CP 0x8000 /* checksum present */ #define GRE_RP 0x4000 /* routing present */ #define GRE_KP 0x2000 /* key present */ #define GRE_SP 0x1000 /* sequence# present */ #define GRE_sP 0x0800 /* source routing */ #define GRE_RECRS 0x0700 /* recursion count */ #define GRE_AP 0x0080 /* acknowledgment# present */ static const struct tok gre_flag_values[] = { { GRE_CP, "checksum present"}, { GRE_RP, "routing present"}, { GRE_KP, "key present"}, { GRE_SP, "sequence# present"}, { GRE_sP, "source routing present"}, { GRE_RECRS, "recursion count"}, { GRE_AP, "ack present"}, { 0, NULL } }; #define GRE_VERS_MASK 0x0007 /* protocol version */ /* source route entry types */ #define GRESRE_IP 0x0800 /* IP */ #define GRESRE_ASN 0xfffe /* ASN */ static void gre_print_0(netdissect_options *, const u_char *, u_int); static void gre_print_1(netdissect_options *, const u_char *, u_int); static int gre_sre_print(netdissect_options *, uint16_t, uint8_t, uint8_t, const u_char *, u_int); static int gre_sre_ip_print(netdissect_options *, uint8_t, uint8_t, const u_char *, u_int); static int gre_sre_asn_print(netdissect_options *, uint8_t, uint8_t, const u_char *, u_int); void gre_print(netdissect_options *ndo, const u_char *bp, u_int length) { u_int len = length, vers; ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; vers = EXTRACT_16BITS(bp) & GRE_VERS_MASK; ND_PRINT((ndo, "GREv%u",vers)); switch(vers) { case 0: gre_print_0(ndo, bp, len); break; case 1: gre_print_1(ndo, bp, len); break; default: ND_PRINT((ndo, " ERROR: unknown-version")); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); return; } static void gre_print_0(netdissect_options *ndo, const u_char *bp, u_int length) { u_int len = length; uint16_t flags, prot; /* 16 bits ND_TCHECKed in gre_print() */ flags = EXTRACT_16BITS(bp); if (ndo->ndo_vflag) ND_PRINT((ndo, ", Flags [%s]", bittok2str(gre_flag_values,"none",flags))); len -= 2; bp += 2; ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; prot = EXTRACT_16BITS(bp); len -= 2; bp += 2; if ((flags & GRE_CP) | (flags & GRE_RP)) { ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; if (ndo->ndo_vflag) ND_PRINT((ndo, ", sum 0x%x", EXTRACT_16BITS(bp))); bp += 2; len -= 2; ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; ND_PRINT((ndo, ", off 0x%x", EXTRACT_16BITS(bp))); bp += 2; len -= 2; } if (flags & GRE_KP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", key=0x%x", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if (flags & GRE_SP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", seq %u", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if (flags & GRE_RP) { for (;;) { uint16_t af; uint8_t sreoff; uint8_t srelen; ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; af = EXTRACT_16BITS(bp); sreoff = *(bp + 2); srelen = *(bp + 3); bp += 4; len -= 4; if (af == 0 && srelen == 0) break; if (!gre_sre_print(ndo, af, sreoff, srelen, bp, len)) goto trunc; if (len < srelen) goto trunc; bp += srelen; len -= srelen; } } if (ndo->ndo_eflag) ND_PRINT((ndo, ", proto %s (0x%04x)", tok2str(ethertype_values,"unknown",prot), prot)); ND_PRINT((ndo, ", length %u",length)); if (ndo->ndo_vflag < 1) ND_PRINT((ndo, ": ")); /* put in a colon as protocol demarc */ else ND_PRINT((ndo, "\n\t")); /* if verbose go multiline */ switch (prot) { case ETHERTYPE_IP: ip_print(ndo, bp, len); break; case ETHERTYPE_IPV6: ip6_print(ndo, bp, len); break; case ETHERTYPE_MPLS: mpls_print(ndo, bp, len); break; case ETHERTYPE_IPX: ipx_print(ndo, bp, len); break; case ETHERTYPE_ATALK: atalk_print(ndo, bp, len); break; case ETHERTYPE_GRE_ISO: isoclns_print(ndo, bp, len); break; case ETHERTYPE_TEB: ether_print(ndo, bp, len, ndo->ndo_snapend - bp, NULL, NULL); break; default: ND_PRINT((ndo, "gre-proto-0x%x", prot)); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void gre_print_1(netdissect_options *ndo, const u_char *bp, u_int length) { u_int len = length; uint16_t flags, prot; /* 16 bits ND_TCHECKed in gre_print() */ flags = EXTRACT_16BITS(bp); len -= 2; bp += 2; if (ndo->ndo_vflag) ND_PRINT((ndo, ", Flags [%s]", bittok2str(gre_flag_values,"none",flags))); ND_TCHECK2(*bp, 2); if (len < 2) goto trunc; prot = EXTRACT_16BITS(bp); len -= 2; bp += 2; if (flags & GRE_KP) { uint32_t k; ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; k = EXTRACT_32BITS(bp); ND_PRINT((ndo, ", call %d", k & 0xffff)); len -= 4; bp += 4; } if (flags & GRE_SP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", seq %u", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if (flags & GRE_AP) { ND_TCHECK2(*bp, 4); if (len < 4) goto trunc; ND_PRINT((ndo, ", ack %u", EXTRACT_32BITS(bp))); bp += 4; len -= 4; } if ((flags & GRE_SP) == 0) ND_PRINT((ndo, ", no-payload")); if (ndo->ndo_eflag) ND_PRINT((ndo, ", proto %s (0x%04x)", tok2str(ethertype_values,"unknown",prot), prot)); ND_PRINT((ndo, ", length %u",length)); if ((flags & GRE_SP) == 0) return; if (ndo->ndo_vflag < 1) ND_PRINT((ndo, ": ")); /* put in a colon as protocol demarc */ else ND_PRINT((ndo, "\n\t")); /* if verbose go multiline */ switch (prot) { case ETHERTYPE_PPP: ppp_print(ndo, bp, len); break; default: ND_PRINT((ndo, "gre-proto-0x%x", prot)); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static int gre_sre_print(netdissect_options *ndo, uint16_t af, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { int ret; switch (af) { case GRESRE_IP: ND_PRINT((ndo, ", (rtaf=ip")); ret = gre_sre_ip_print(ndo, sreoff, srelen, bp, len); ND_PRINT((ndo, ")")); break; case GRESRE_ASN: ND_PRINT((ndo, ", (rtaf=asn")); ret = gre_sre_asn_print(ndo, sreoff, srelen, bp, len); ND_PRINT((ndo, ")")); break; default: ND_PRINT((ndo, ", (rtaf=0x%x)", af)); ret = 1; } return (ret); } static int gre_sre_ip_print(netdissect_options *ndo, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { const u_char *up = bp; char buf[INET_ADDRSTRLEN]; if (sreoff & 3) { ND_PRINT((ndo, ", badoffset=%u", sreoff)); return (1); } if (srelen & 3) { ND_PRINT((ndo, ", badlength=%u", srelen)); return (1); } if (sreoff >= srelen) { ND_PRINT((ndo, ", badoff/len=%u/%u", sreoff, srelen)); return (1); } while (srelen != 0) { if (!ND_TTEST2(*bp, 4)) return (0); if (len < 4) return (0); addrtostr(bp, buf, sizeof(buf)); ND_PRINT((ndo, " %s%s", ((bp - up) == sreoff) ? "*" : "", buf)); bp += 4; len -= 4; srelen -= 4; } return (1); } static int gre_sre_asn_print(netdissect_options *ndo, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { const u_char *up = bp; if (sreoff & 1) { ND_PRINT((ndo, ", badoffset=%u", sreoff)); return (1); } if (srelen & 1) { ND_PRINT((ndo, ", badlength=%u", srelen)); return (1); } if (sreoff >= srelen) { ND_PRINT((ndo, ", badoff/len=%u/%u", sreoff, srelen)); return (1); } while (srelen != 0) { if (!ND_TTEST2(*bp, 2)) return (0); if (len < 2) return (0); ND_PRINT((ndo, " %s%x", ((bp - up) == sreoff) ? "*" : "", EXTRACT_16BITS(bp))); bp += 2; len -= 2; srelen -= 2; } return (1); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_5
crossvul-cpp_data_bad_3068_1
/* * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_CHACHA # include <openssl/evp.h> # include <openssl/objects.h> # include "evp_locl.h" # include "internal/evp_int.h" # include "internal/chacha.h" typedef struct { union { double align; /* this ensures even sizeof(EVP_CHACHA_KEY)%8==0 */ unsigned int d[CHACHA_KEY_SIZE / 4]; } key; unsigned int counter[CHACHA_CTR_SIZE / 4]; unsigned char buf[CHACHA_BLK_SIZE]; unsigned int partial_len; } EVP_CHACHA_KEY; #define data(ctx) ((EVP_CHACHA_KEY *)(ctx)->cipher_data) static int chacha_init_key(EVP_CIPHER_CTX *ctx, const unsigned char user_key[CHACHA_KEY_SIZE], const unsigned char iv[CHACHA_CTR_SIZE], int enc) { EVP_CHACHA_KEY *key = data(ctx); unsigned int i; if (user_key) for (i = 0; i < CHACHA_KEY_SIZE; i+=4) { key->key.d[i/4] = CHACHA_U8TOU32(user_key+i); } if (iv) for (i = 0; i < CHACHA_CTR_SIZE; i+=4) { key->counter[i/4] = CHACHA_U8TOU32(iv+i); } key->partial_len = 0; return 1; } static int chacha_cipher(EVP_CIPHER_CTX * ctx, unsigned char *out, const unsigned char *inp, size_t len) { EVP_CHACHA_KEY *key = data(ctx); unsigned int n, rem, ctr32; if ((n = key->partial_len)) { while (len && n < CHACHA_BLK_SIZE) { *out++ = *inp++ ^ key->buf[n++]; len--; } key->partial_len = n; if (len == 0) return 1; if (n == CHACHA_BLK_SIZE) { key->partial_len = 0; key->counter[0]++; if (key->counter[0] == 0) key->counter[1]++; } } rem = (unsigned int)(len % CHACHA_BLK_SIZE); len -= rem; ctr32 = key->counter[0]; while (len >= CHACHA_BLK_SIZE) { size_t blocks = len / CHACHA_BLK_SIZE; /* * 1<<28 is just a not-so-small yet not-so-large number... * Below condition is practically never met, but it has to * be checked for code correctness. */ if (sizeof(size_t)>sizeof(unsigned int) && blocks>(1U<<28)) blocks = (1U<<28); /* * As ChaCha20_ctr32 operates on 32-bit counter, caller * has to handle overflow. 'if' below detects the * overflow, which is then handled by limiting the * amount of blocks to the exact overflow point... */ ctr32 += (unsigned int)blocks; if (ctr32 < blocks) { blocks -= ctr32; ctr32 = 0; } blocks *= CHACHA_BLK_SIZE; ChaCha20_ctr32(out, inp, blocks, key->key.d, key->counter); len -= blocks; inp += blocks; out += blocks; key->counter[0] = ctr32; if (ctr32 == 0) key->counter[1]++; } if (rem) { memset(key->buf, 0, sizeof(key->buf)); ChaCha20_ctr32(key->buf, key->buf, CHACHA_BLK_SIZE, key->key.d, key->counter); for (n = 0; n < rem; n++) out[n] = inp[n] ^ key->buf[n]; key->partial_len = rem; } return 1; } static const EVP_CIPHER chacha20 = { NID_chacha20, 1, /* block_size */ CHACHA_KEY_SIZE, /* key_len */ CHACHA_CTR_SIZE, /* iv_len, 128-bit counter in the context */ EVP_CIPH_CUSTOM_IV | EVP_CIPH_ALWAYS_CALL_INIT, chacha_init_key, chacha_cipher, NULL, sizeof(EVP_CHACHA_KEY), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_chacha20(void) { return (&chacha20); } # ifndef OPENSSL_NO_POLY1305 # include "internal/poly1305.h" typedef struct { EVP_CHACHA_KEY key; unsigned int nonce[12/4]; unsigned char tag[POLY1305_BLOCK_SIZE]; struct { uint64_t aad, text; } len; int aad, mac_inited, tag_len, nonce_len; size_t tls_payload_length; } EVP_CHACHA_AEAD_CTX; # define NO_TLS_PAYLOAD_LENGTH ((size_t)-1) # define aead_data(ctx) ((EVP_CHACHA_AEAD_CTX *)(ctx)->cipher_data) # define POLY1305_ctx(actx) ((POLY1305 *)(actx + 1)) static int chacha20_poly1305_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *inkey, const unsigned char *iv, int enc) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); if (!inkey && !iv) return 1; actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (iv != NULL) { unsigned char temp[CHACHA_CTR_SIZE] = { 0 }; /* pad on the left */ if (actx->nonce_len <= CHACHA_CTR_SIZE) memcpy(temp + CHACHA_CTR_SIZE - actx->nonce_len, iv, actx->nonce_len); chacha_init_key(ctx, inkey, temp, enc); actx->nonce[0] = actx->key.counter[1]; actx->nonce[1] = actx->key.counter[2]; actx->nonce[2] = actx->key.counter[3]; } else { chacha_init_key(ctx, inkey, NULL, enc); } return 1; } static int chacha20_poly1305_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); size_t rem, plen = actx->tls_payload_length; static const unsigned char zero[POLY1305_BLOCK_SIZE] = { 0 }; if (!actx->mac_inited) { actx->key.counter[0] = 0; memset(actx->key.buf, 0, sizeof(actx->key.buf)); ChaCha20_ctr32(actx->key.buf, actx->key.buf, CHACHA_BLK_SIZE, actx->key.key.d, actx->key.counter); Poly1305_Init(POLY1305_ctx(actx), actx->key.buf); actx->key.counter[0] = 1; actx->key.partial_len = 0; actx->len.aad = actx->len.text = 0; actx->mac_inited = 1; } if (in) { /* aad or text */ if (out == NULL) { /* aad */ Poly1305_Update(POLY1305_ctx(actx), in, len); actx->len.aad += len; actx->aad = 1; return len; } else { /* plain- or ciphertext */ if (actx->aad) { /* wrap up aad */ if ((rem = (size_t)actx->len.aad % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); actx->aad = 0; } actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (plen == NO_TLS_PAYLOAD_LENGTH) plen = len; else if (len != plen + POLY1305_BLOCK_SIZE) return -1; if (ctx->encrypt) { /* plaintext */ chacha_cipher(ctx, out, in, plen); Poly1305_Update(POLY1305_ctx(actx), out, plen); in += plen; out += plen; actx->len.text += plen; } else { /* ciphertext */ Poly1305_Update(POLY1305_ctx(actx), in, plen); chacha_cipher(ctx, out, in, plen); in += plen; out += plen; actx->len.text += plen; } } } if (in == NULL /* explicit final */ || plen != len) { /* or tls mode */ const union { long one; char little; } is_endian = { 1 }; unsigned char temp[POLY1305_BLOCK_SIZE]; if (actx->aad) { /* wrap up aad */ if ((rem = (size_t)actx->len.aad % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); actx->aad = 0; } if ((rem = (size_t)actx->len.text % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); if (is_endian.little) { Poly1305_Update(POLY1305_ctx(actx), (unsigned char *)&actx->len, POLY1305_BLOCK_SIZE); } else { temp[0] = (unsigned char)(actx->len.aad); temp[1] = (unsigned char)(actx->len.aad>>8); temp[2] = (unsigned char)(actx->len.aad>>16); temp[3] = (unsigned char)(actx->len.aad>>24); temp[4] = (unsigned char)(actx->len.aad>>32); temp[5] = (unsigned char)(actx->len.aad>>40); temp[6] = (unsigned char)(actx->len.aad>>48); temp[7] = (unsigned char)(actx->len.aad>>56); temp[8] = (unsigned char)(actx->len.text); temp[9] = (unsigned char)(actx->len.text>>8); temp[10] = (unsigned char)(actx->len.text>>16); temp[11] = (unsigned char)(actx->len.text>>24); temp[12] = (unsigned char)(actx->len.text>>32); temp[13] = (unsigned char)(actx->len.text>>40); temp[14] = (unsigned char)(actx->len.text>>48); temp[15] = (unsigned char)(actx->len.text>>56); Poly1305_Update(POLY1305_ctx(actx), temp, POLY1305_BLOCK_SIZE); } Poly1305_Final(POLY1305_ctx(actx), ctx->encrypt ? actx->tag : temp); actx->mac_inited = 0; if (in != NULL && len != plen) { /* tls mode */ if (ctx->encrypt) { memcpy(out, actx->tag, POLY1305_BLOCK_SIZE); } else { if (CRYPTO_memcmp(temp, in, POLY1305_BLOCK_SIZE)) { memset(out - plen, 0, plen); return -1; } } } else if (!ctx->encrypt) { if (CRYPTO_memcmp(temp, actx->tag, actx->tag_len)) return -1; } } return len; } static int chacha20_poly1305_cleanup(EVP_CIPHER_CTX *ctx) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); if (actx) OPENSSL_cleanse(ctx->cipher_data, sizeof(*ctx) + Poly1305_ctx_size()); return 1; } static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); switch(type) { case EVP_CTRL_INIT: if (actx == NULL) actx = ctx->cipher_data = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size()); if (actx == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR); return 0; } actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tag_len = 0; actx->nonce_len = 12; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; return 1; case EVP_CTRL_COPY: if (actx) { EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr; dst->cipher_data = OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size()); if (dst->cipher_data == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR); return 0; } } return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0 || arg > CHACHA_CTR_SIZE) return 0; actx->nonce_len = arg; return 1; case EVP_CTRL_AEAD_SET_IV_FIXED: if (arg != 12) return 0; actx->nonce[0] = actx->key.counter[1] = CHACHA_U8TOU32((unsigned char *)ptr); actx->nonce[1] = actx->key.counter[2] = CHACHA_U8TOU32((unsigned char *)ptr+4); actx->nonce[2] = actx->key.counter[3] = CHACHA_U8TOU32((unsigned char *)ptr+8); return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE) return 0; if (ptr != NULL) { memcpy(actx->tag, ptr, arg); actx->tag_len = arg; } return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt) return 0; memcpy(ptr, actx->tag, arg); return 1; case EVP_CTRL_AEAD_TLS1_AAD: if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; { unsigned int len; unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE]; len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 | aad[EVP_AEAD_TLS1_AAD_LEN - 1]; if (!ctx->encrypt) { len -= POLY1305_BLOCK_SIZE; /* discount attached tag */ memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2); aad = temp; temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8); temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len; } actx->tls_payload_length = len; /* * merge record sequence number as per * draft-ietf-tls-chacha20-poly1305-03 */ actx->key.counter[1] = actx->nonce[0]; actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad); actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4); actx->mac_inited = 0; chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN); return POLY1305_BLOCK_SIZE; /* tag length */ } case EVP_CTRL_AEAD_SET_MAC_KEY: /* no-op */ return 1; default: return -1; } } static EVP_CIPHER chacha20_poly1305 = { NID_chacha20_poly1305, 1, /* block_size */ CHACHA_KEY_SIZE, /* key_len */ 12, /* iv_len, 96-bit nonce in the context */ EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_CUSTOM_IV | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_CUSTOM_CIPHER, chacha20_poly1305_init_key, chacha20_poly1305_cipher, chacha20_poly1305_cleanup, 0, /* 0 moves context-specific structure allocation to ctrl */ NULL, /* set_asn1_parameters */ NULL, /* get_asn1_parameters */ chacha20_poly1305_ctrl, NULL /* app_data */ }; const EVP_CIPHER *EVP_chacha20_poly1305(void) { return(&chacha20_poly1305); } # endif #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3068_1
crossvul-cpp_data_good_5306_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 "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/constitute.h" #include "magick/distort.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility.h" #include "magick/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(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); switch (bpp) { case 1: /* Convert bitmap scanline. */ { 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=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { 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+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { 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,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { 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; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ 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,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (!SyncAuthenticPixels(image,exception)) break; break; } } /* Helper for WPG1 raster reader. */ #define InsertByte(b) \ { \ BImgBuff[x]=b; \ x++; \ if((ssize_t) x>=ldblk) \ { \ InsertRow(BImgBuff,(ssize_t) y,image,bpp); \ x=0; \ y++; \ } \ } /* WPG1 raster reader. */ static int UnpackWPGRaster(Image *image,int bpp) { 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(BImgBuff,y-1,image,bpp); } } } } 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(BImgBuff,(ssize_t) y,image,bpp); \ x=0; \ y++; \ } \ } /* WPG2 raster reader. */ static int UnpackWPG2Raster(Image *image,int bpp) { int XorMe = 0; int RunCount; 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(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), image,bpp); 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); } } } } 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[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; 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*MaxTextExtent, 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*MaxTextExtent,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,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,"%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,MaxTextExtent); (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent); 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 == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); 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->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=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)) 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->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=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)) { 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=(PixelPacket *) 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) < 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); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=0; 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) == 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)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) 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,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 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); 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); if (status == MagickFalse) { InheritException(exception,&image->exception); 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=SetMagickInfo("WPG"); entry->decoder=(DecodeImageHandler *) ReadWPGImage; entry->magick=(IsImageFormatHandler *) IsWPG; entry->description=AcquireString("Word Perfect Graphics"); entry->module=ConstantString("WPG"); entry->seekable_stream=MagickTrue; (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-125/c/good_5306_0
crossvul-cpp_data_bad_2671_0
/* * Copyright (c) 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Original code by Matt Thomas, Digital Equipment Corporation * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete IS-IS & CLNP support. */ /* \summary: ISO CLNS, ESIS, and ISIS printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "ether.h" #include "nlpid.h" #include "extract.h" #include "gmpls.h" #include "oui.h" #include "signature.h" static const char tstr[] = " [|isis]"; /* * IS-IS is defined in ISO 10589. Look there for protocol definitions. */ #define SYSTEM_ID_LEN ETHER_ADDR_LEN #define NODE_ID_LEN SYSTEM_ID_LEN+1 #define LSP_ID_LEN SYSTEM_ID_LEN+2 #define ISIS_VERSION 1 #define ESIS_VERSION 1 #define CLNP_VERSION 1 #define ISIS_PDU_TYPE_MASK 0x1F #define ESIS_PDU_TYPE_MASK 0x1F #define CLNP_PDU_TYPE_MASK 0x1F #define CLNP_FLAG_MASK 0xE0 #define ISIS_LAN_PRIORITY_MASK 0x7F #define ISIS_PDU_L1_LAN_IIH 15 #define ISIS_PDU_L2_LAN_IIH 16 #define ISIS_PDU_PTP_IIH 17 #define ISIS_PDU_L1_LSP 18 #define ISIS_PDU_L2_LSP 20 #define ISIS_PDU_L1_CSNP 24 #define ISIS_PDU_L2_CSNP 25 #define ISIS_PDU_L1_PSNP 26 #define ISIS_PDU_L2_PSNP 27 static const struct tok isis_pdu_values[] = { { ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"}, { ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"}, { ISIS_PDU_PTP_IIH, "p2p IIH"}, { ISIS_PDU_L1_LSP, "L1 LSP"}, { ISIS_PDU_L2_LSP, "L2 LSP"}, { ISIS_PDU_L1_CSNP, "L1 CSNP"}, { ISIS_PDU_L2_CSNP, "L2 CSNP"}, { ISIS_PDU_L1_PSNP, "L1 PSNP"}, { ISIS_PDU_L2_PSNP, "L2 PSNP"}, { 0, NULL} }; /* * A TLV is a tuple of a type, length and a value and is normally used for * encoding information in all sorts of places. This is an enumeration of * the well known types. * * list taken from rfc3359 plus some memory from veterans ;-) */ #define ISIS_TLV_AREA_ADDR 1 /* iso10589 */ #define ISIS_TLV_IS_REACH 2 /* iso10589 */ #define ISIS_TLV_ESNEIGH 3 /* iso10589 */ #define ISIS_TLV_PART_DIS 4 /* iso10589 */ #define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */ #define ISIS_TLV_ISNEIGH 6 /* iso10589 */ #define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */ #define ISIS_TLV_PADDING 8 /* iso10589 */ #define ISIS_TLV_LSP 9 /* iso10589 */ #define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */ #define ISIS_TLV_CHECKSUM 12 /* rfc3358 */ #define ISIS_TLV_CHECKSUM_MINLEN 2 #define ISIS_TLV_POI 13 /* rfc6232 */ #define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */ #define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2 #define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */ #define ISIS_TLV_DECNET_PHASE4 42 #define ISIS_TLV_LUCENT_PRIVATE 66 #define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */ #define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */ #define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */ #define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */ #define ISIS_TLV_IDRP_INFO_MINLEN 1 #define ISIS_TLV_IPADDR 132 /* rfc1195 */ #define ISIS_TLV_IPAUTH 133 /* rfc1195 */ #define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_HOSTNAME 137 /* rfc2763 */ #define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */ #define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */ #define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */ #define ISIS_TLV_NORTEL_PRIVATE1 176 #define ISIS_TLV_NORTEL_PRIVATE2 177 #define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */ #define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1 #define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2 #define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED_MINLEN 2 #define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */ #define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */ #define ISIS_TLV_IIH_SEQNR_MINLEN 4 #define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */ #define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3 static const struct tok isis_tlv_values[] = { { ISIS_TLV_AREA_ADDR, "Area address(es)"}, { ISIS_TLV_IS_REACH, "IS Reachability"}, { ISIS_TLV_ESNEIGH, "ES Neighbor(s)"}, { ISIS_TLV_PART_DIS, "Partition DIS"}, { ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"}, { ISIS_TLV_ISNEIGH, "IS Neighbor(s)"}, { ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"}, { ISIS_TLV_PADDING, "Padding"}, { ISIS_TLV_LSP, "LSP entries"}, { ISIS_TLV_AUTH, "Authentication"}, { ISIS_TLV_CHECKSUM, "Checksum"}, { ISIS_TLV_POI, "Purge Originator Identifier"}, { ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"}, { ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"}, { ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"}, { ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"}, { ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"}, { ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"}, { ISIS_TLV_PROTOCOLS, "Protocols supported"}, { ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"}, { ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"}, { ISIS_TLV_IPADDR, "IPv4 Interface address(es)"}, { ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"}, { ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"}, { ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"}, { ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"}, { ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"}, { ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"}, { ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"}, { ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"}, { ISIS_TLV_HOSTNAME, "Hostname"}, { ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"}, { ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"}, { ISIS_TLV_MT_SUPPORTED, "Multi Topology"}, { ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"}, { ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"}, { ISIS_TLV_IP6_REACH, "IPv6 reachability"}, { ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"}, { ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"}, { ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"}, { ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"}, { 0, NULL } }; #define ESIS_OPTION_PROTOCOLS 129 #define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */ #define ESIS_OPTION_SECURITY 197 /* iso9542 */ #define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */ #define ESIS_OPTION_PRIORITY 205 /* iso9542 */ #define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */ #define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */ static const struct tok esis_option_values[] = { { ESIS_OPTION_PROTOCOLS, "Protocols supported"}, { ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" }, { ESIS_OPTION_SECURITY, "Security" }, { ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" }, { ESIS_OPTION_PRIORITY, "Priority" }, { ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" }, { ESIS_OPTION_SNPA_MASK, "SNPA Mask" }, { 0, NULL } }; #define CLNP_OPTION_DISCARD_REASON 193 #define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */ #define CLNP_OPTION_SECURITY 197 /* iso8473 */ #define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */ #define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */ #define CLNP_OPTION_PADDING 204 /* iso8473 */ #define CLNP_OPTION_PRIORITY 205 /* iso8473 */ static const struct tok clnp_option_values[] = { { CLNP_OPTION_DISCARD_REASON, "Discard Reason"}, { CLNP_OPTION_PRIORITY, "Priority"}, { CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"}, { CLNP_OPTION_SECURITY, "Security"}, { CLNP_OPTION_SOURCE_ROUTING, "Source Routing"}, { CLNP_OPTION_ROUTE_RECORDING, "Route Recording"}, { CLNP_OPTION_PADDING, "Padding"}, { 0, NULL } }; static const struct tok clnp_option_rfd_class_values[] = { { 0x0, "General"}, { 0x8, "Address"}, { 0x9, "Source Routeing"}, { 0xa, "Lifetime"}, { 0xb, "PDU Discarded"}, { 0xc, "Reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_general_values[] = { { 0x0, "Reason not specified"}, { 0x1, "Protocol procedure error"}, { 0x2, "Incorrect checksum"}, { 0x3, "PDU discarded due to congestion"}, { 0x4, "Header syntax error (cannot be parsed)"}, { 0x5, "Segmentation needed but not permitted"}, { 0x6, "Incomplete PDU received"}, { 0x7, "Duplicate option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_address_values[] = { { 0x0, "Destination address unreachable"}, { 0x1, "Destination address unknown"}, { 0, NULL } }; static const struct tok clnp_option_rfd_source_routeing_values[] = { { 0x0, "Unspecified source routeing error"}, { 0x1, "Syntax error in source routeing field"}, { 0x2, "Unknown address in source routeing field"}, { 0x3, "Path not acceptable"}, { 0, NULL } }; static const struct tok clnp_option_rfd_lifetime_values[] = { { 0x0, "Lifetime expired while data unit in transit"}, { 0x1, "Lifetime expired during reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_pdu_discard_values[] = { { 0x0, "Unsupported option not specified"}, { 0x1, "Unsupported protocol version"}, { 0x2, "Unsupported security option"}, { 0x3, "Unsupported source routeing option"}, { 0x4, "Unsupported recording of route option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_reassembly_values[] = { { 0x0, "Reassembly interference"}, { 0, NULL } }; /* array of 16 error-classes */ static const struct tok *clnp_option_rfd_error_class[] = { clnp_option_rfd_general_values, NULL, NULL, NULL, NULL, NULL, NULL, NULL, clnp_option_rfd_address_values, clnp_option_rfd_source_routeing_values, clnp_option_rfd_lifetime_values, clnp_option_rfd_pdu_discard_values, clnp_option_rfd_reassembly_values, NULL, NULL, NULL }; #define CLNP_OPTION_OPTION_QOS_MASK 0x3f #define CLNP_OPTION_SCOPE_MASK 0xc0 #define CLNP_OPTION_SCOPE_SA_SPEC 0x40 #define CLNP_OPTION_SCOPE_DA_SPEC 0x80 #define CLNP_OPTION_SCOPE_GLOBAL 0xc0 static const struct tok clnp_option_scope_values[] = { { CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"}, { CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"}, { CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_values[] = { { 0x0, "partial"}, { 0x1, "complete"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_string_values[] = { { CLNP_OPTION_SOURCE_ROUTING, "source routing"}, { CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"}, { 0, NULL } }; static const struct tok clnp_option_qos_global_values[] = { { 0x20, "reserved"}, { 0x10, "sequencing vs. delay"}, { 0x08, "congested"}, { 0x04, "delay vs. cost"}, { 0x02, "error vs. delay"}, { 0x01, "error vs. cost"}, { 0, NULL } }; #define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */ #define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */ #define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */ static const struct tok isis_ext_is_reach_subtlv_values[] = { { ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" }, { ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" }, { ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" }, { ISIS_SUBTLV_SPB_METRIC, "SPB Metric" }, { 250, "Reserved for cisco specific extensions" }, { 251, "Reserved for cisco specific extensions" }, { 252, "Reserved for cisco specific extensions" }, { 253, "Reserved for cisco specific extensions" }, { 254, "Reserved for cisco specific extensions" }, { 255, "Reserved for future expansion" }, { 0, NULL } }; #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */ static const struct tok isis_ext_ip_reach_subtlv_values[] = { { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" }, { 0, NULL } }; static const struct tok isis_subtlv_link_attribute_values[] = { { 0x01, "Local Protection Available" }, { 0x02, "Link excluded from local protection path" }, { 0x04, "Local maintenance required"}, { 0, NULL } }; #define ISIS_SUBTLV_AUTH_SIMPLE 1 #define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */ #define ISIS_SUBTLV_AUTH_MD5 54 #define ISIS_SUBTLV_AUTH_MD5_LEN 16 #define ISIS_SUBTLV_AUTH_PRIVATE 255 static const struct tok isis_subtlv_auth_values[] = { { ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"}, { ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"}, { ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"}, { ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"}, { 0, NULL } }; #define ISIS_SUBTLV_IDRP_RES 0 #define ISIS_SUBTLV_IDRP_LOCAL 1 #define ISIS_SUBTLV_IDRP_ASN 2 static const struct tok isis_subtlv_idrp_values[] = { { ISIS_SUBTLV_IDRP_RES, "Reserved"}, { ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"}, { ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"}, { 0, NULL} }; #define ISIS_SUBTLV_SPB_MCID 4 #define ISIS_SUBTLV_SPB_DIGEST 5 #define ISIS_SUBTLV_SPB_BVID 6 #define ISIS_SUBTLV_SPB_INSTANCE 1 #define ISIS_SUBTLV_SPBM_SI 3 #define ISIS_SPB_MCID_LEN 51 #define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102 #define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33 #define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6 #define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19 #define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8 static const struct tok isis_mt_port_cap_subtlv_values[] = { { ISIS_SUBTLV_SPB_MCID, "SPB MCID" }, { ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" }, { ISIS_SUBTLV_SPB_BVID, "SPB BVID" }, { 0, NULL } }; static const struct tok isis_mt_capability_subtlv_values[] = { { ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" }, { ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" }, { 0, NULL } }; struct isis_spb_mcid { uint8_t format_id; uint8_t name[32]; uint8_t revision_lvl[2]; uint8_t digest[16]; }; struct isis_subtlv_spb_mcid { struct isis_spb_mcid mcid; struct isis_spb_mcid aux_mcid; }; struct isis_subtlv_spb_instance { uint8_t cist_root_id[8]; uint8_t cist_external_root_path_cost[4]; uint8_t bridge_priority[2]; uint8_t spsourceid[4]; uint8_t no_of_trees; }; #define CLNP_SEGMENT_PART 0x80 #define CLNP_MORE_SEGMENTS 0x40 #define CLNP_REQUEST_ER 0x20 static const struct tok clnp_flag_values[] = { { CLNP_SEGMENT_PART, "Segmentation permitted"}, { CLNP_MORE_SEGMENTS, "more Segments"}, { CLNP_REQUEST_ER, "request Error Report"}, { 0, NULL} }; #define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4) #define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3) #define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80) #define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78) #define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40) #define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20) #define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10) #define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8) #define ISIS_MASK_MTID(x) ((x)&0x0fff) #define ISIS_MASK_MTFLAGS(x) ((x)&0xf000) static const struct tok isis_mt_flag_values[] = { { 0x4000, "ATT bit set"}, { 0x8000, "Overload bit set"}, { 0, NULL} }; #define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80) #define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20) #define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40) #define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f) #define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1) static const struct tok isis_mt_values[] = { { 0, "IPv4 unicast"}, { 1, "In-Band Management"}, { 2, "IPv6 unicast"}, { 3, "Multicast"}, { 4095, "Development, Experimental or Proprietary"}, { 0, NULL } }; static const struct tok isis_iih_circuit_type_values[] = { { 1, "Level 1 only"}, { 2, "Level 2 only"}, { 3, "Level 1, Level 2"}, { 0, NULL} }; #define ISIS_LSP_TYPE_UNUSED0 0 #define ISIS_LSP_TYPE_LEVEL_1 1 #define ISIS_LSP_TYPE_UNUSED2 2 #define ISIS_LSP_TYPE_LEVEL_2 3 static const struct tok isis_lsp_istype_values[] = { { ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_1, "L1 IS"}, { ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_2, "L2 IS"}, { 0, NULL } }; /* * Katz's point to point adjacency TLV uses codes to tell us the state of * the remote adjacency. Enumerate them. */ #define ISIS_PTP_ADJ_UP 0 #define ISIS_PTP_ADJ_INIT 1 #define ISIS_PTP_ADJ_DOWN 2 static const struct tok isis_ptp_adjancey_values[] = { { ISIS_PTP_ADJ_UP, "Up" }, { ISIS_PTP_ADJ_INIT, "Initializing" }, { ISIS_PTP_ADJ_DOWN, "Down" }, { 0, NULL} }; struct isis_tlv_ptp_adj { uint8_t adjacency_state; uint8_t extd_local_circuit_id[4]; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; uint8_t neighbor_extd_local_circuit_id[4]; }; static void osi_print_cksum(netdissect_options *, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length); static int clnp_print(netdissect_options *, const uint8_t *, u_int); static void esis_print(netdissect_options *, const uint8_t *, u_int); static int isis_print(netdissect_options *, const uint8_t *, u_int); struct isis_metric_block { uint8_t metric_default; uint8_t metric_delay; uint8_t metric_expense; uint8_t metric_error; }; struct isis_tlv_is_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_nodeid[NODE_ID_LEN]; }; struct isis_tlv_es_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; }; struct isis_tlv_ip_reach { struct isis_metric_block isis_metric_block; uint8_t prefix[4]; uint8_t mask[4]; }; static const struct tok isis_is_reach_virtual_values[] = { { 0, "IsNotVirtual"}, { 1, "IsVirtual"}, { 0, NULL } }; static const struct tok isis_restart_flag_values[] = { { 0x1, "Restart Request"}, { 0x2, "Restart Acknowledgement"}, { 0x4, "Suppress adjacency advertisement"}, { 0, NULL } }; struct isis_common_header { uint8_t nlpid; uint8_t fixed_len; uint8_t version; /* Protocol version */ uint8_t id_length; uint8_t pdu_type; /* 3 MSbits are reserved */ uint8_t pdu_version; /* Packet format version */ uint8_t reserved; uint8_t max_area; }; struct isis_iih_lan_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t priority; uint8_t lan_id[NODE_ID_LEN]; }; struct isis_iih_ptp_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t circuit_id; }; struct isis_lsp_header { uint8_t pdu_len[2]; uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; uint8_t typeblock; }; struct isis_csnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; uint8_t start_lsp_id[LSP_ID_LEN]; uint8_t end_lsp_id[LSP_ID_LEN]; }; struct isis_psnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; }; struct isis_tlv_lsp { uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; }; #define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header)) #define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header)) #define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header)) #define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header)) #define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header)) #define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header)) void isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length) { if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */ ND_PRINT((ndo, "|OSI")); return; } if (ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p)); switch (*p) { case NLPID_CLNP: if (!clnp_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_ESIS: esis_print(ndo, p, length); return; case NLPID_ISIS: if (!isis_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_NULLNS: ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); break; case NLPID_Q933: q933_print(ndo, p + 1, length - 1); break; case NLPID_IP: ip_print(ndo, p + 1, length - 1); break; case NLPID_IP6: ip6_print(ndo, p + 1, length - 1); break; case NLPID_PPP: ppp_print(ndo, p + 1, length - 1); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p)); ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); if (length > 1) print_unknown_data(ndo, p, "\n\t", length); break; } } #define CLNP_PDU_ER 1 #define CLNP_PDU_DT 28 #define CLNP_PDU_MD 29 #define CLNP_PDU_ERQ 30 #define CLNP_PDU_ERP 31 static const struct tok clnp_pdu_values[] = { { CLNP_PDU_ER, "Error Report"}, { CLNP_PDU_MD, "MD"}, { CLNP_PDU_DT, "Data"}, { CLNP_PDU_ERQ, "Echo Request"}, { CLNP_PDU_ERP, "Echo Response"}, { 0, NULL } }; struct clnp_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t lifetime; /* units of 500ms */ uint8_t type; uint8_t segment_length[2]; uint8_t cksum[2]; }; struct clnp_segment_header_t { uint8_t data_unit_id[2]; uint8_t segment_offset[2]; uint8_t total_length[2]; }; /* * clnp_print * Decode CLNP packets. Return 0 on error. */ static int clnp_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr,*source_address,*dest_address; u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags; const struct clnp_header_t *clnp_header; const struct clnp_segment_header_t *clnp_segment_header; uint8_t rfd_error_major,rfd_error_minor; clnp_header = (const struct clnp_header_t *) pptr; ND_TCHECK(*clnp_header); li = clnp_header->length_indicator; optr = pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "CLNP")); /* * Sanity checking of the header. */ if (clnp_header->version != CLNP_VERSION) { ND_PRINT((ndo, "version %d packet not supported", clnp_header->version)); return (0); } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return (0); } if (li < sizeof(struct clnp_header_t)) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return (0); } /* FIXME further header sanity checking */ clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK; clnp_flags = clnp_header->type & CLNP_FLAG_MASK; pptr += sizeof(struct clnp_header_t); li -= sizeof(struct clnp_header_t); if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); dest_address_length = *pptr; pptr += 1; li -= 1; if (li < dest_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, dest_address_length); dest_address = pptr; pptr += dest_address_length; li -= dest_address_length; if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); source_address_length = *pptr; pptr += 1; li -= 1; if (li < source_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, source_address_length); source_address = pptr; pptr += source_address_length; li -= source_address_length; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s > %s, %s, length %u", ndo->ndo_eflag ? "" : ", ", isonsap_string(ndo, source_address, source_address_length), isonsap_string(ndo, dest_address, dest_address_length), tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type), length)); return (1); } ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x", tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type), clnp_header->length_indicator, clnp_header->version, clnp_header->lifetime/2, (clnp_header->lifetime%2)*5, EXTRACT_16BITS(clnp_header->segment_length), EXTRACT_16BITS(clnp_header->cksum))); osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7, clnp_header->length_indicator); ND_PRINT((ndo, "\n\tFlags [%s]", bittok2str(clnp_flag_values, "none", clnp_flags))); ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length), dest_address_length, isonsap_string(ndo, dest_address, dest_address_length))); if (clnp_flags & CLNP_SEGMENT_PART) { if (li < sizeof(const struct clnp_segment_header_t)) { ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part")); return (0); } clnp_segment_header = (const struct clnp_segment_header_t *) pptr; ND_TCHECK(*clnp_segment_header); ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u", EXTRACT_16BITS(clnp_segment_header->data_unit_id), EXTRACT_16BITS(clnp_segment_header->segment_offset), EXTRACT_16BITS(clnp_segment_header->total_length))); pptr+=sizeof(const struct clnp_segment_header_t); li-=sizeof(const struct clnp_segment_header_t); } /* now walk the options */ while (li >= 2) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return (0); } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return (0); } ND_TCHECK2(*pptr, opli); li -= opli; tptr = pptr; tlen = opli; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(clnp_option_values,"Unknown",op), op, opli)); /* * We've already checked that the entire option is present * in the captured packet with the ND_TCHECK2() call. * Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2() * checks. * We do, however, need to check tlen, to make sure we * don't run past the end of the option. */ switch (op) { case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */ case CLNP_OPTION_SOURCE_ROUTING: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "%s %s", tok2str(clnp_option_sr_rr_values,"Unknown",*tptr), tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op))); nsap_offset=*(tptr+1); if (nsap_offset == 0) { ND_PRINT((ndo, " Bad NSAP offset (0)")); break; } nsap_offset-=1; /* offset to nsap list */ if (nsap_offset > tlen) { ND_PRINT((ndo, " Bad NSAP offset (past end of option)")); break; } tptr+=nsap_offset; tlen-=nsap_offset; while (tlen > 0) { source_address_length=*tptr; if (tlen < source_address_length+1) { ND_PRINT((ndo, "\n\t NSAP address goes past end of option")); break; } if (source_address_length > 0) { source_address=(tptr+1); ND_TCHECK2(*source_address, source_address_length); ND_PRINT((ndo, "\n\t NSAP address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length))); } tlen-=source_address_length+1; } break; case CLNP_OPTION_PRIORITY: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "0x%1x", *tptr&0x0f)); break; case CLNP_OPTION_QOS_MAINTENANCE: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s", tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK))); if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL) ND_PRINT((ndo, "\n\t QoS Flags [%s]", bittok2str(clnp_option_qos_global_values, "none", *tptr&CLNP_OPTION_OPTION_QOS_MASK))); break; case CLNP_OPTION_SECURITY: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u", tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK), *(tptr+1))); break; case CLNP_OPTION_DISCARD_REASON: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } rfd_error_major = (*tptr&0xf0) >> 4; rfd_error_minor = *tptr&0x0f; ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)", tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major), rfd_error_major, tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor), rfd_error_minor)); break; case CLNP_OPTION_PADDING: ND_PRINT((ndo, "padding data")); break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } switch (clnp_pdu_type) { case CLNP_PDU_ER: /* fall through */ case CLNP_PDU_ERP: ND_TCHECK(*pptr); if (*(pptr) == NLPID_CLNP) { ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); /* FIXME recursion protection */ clnp_print(ndo, pptr, length - clnp_header->length_indicator); break; } case CLNP_PDU_DT: case CLNP_PDU_MD: case CLNP_PDU_ERQ: default: /* dump the PDU specific data */ if (length-(pptr-optr) > 0) { ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator)); print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr)); } } return (1); trunc: ND_PRINT((ndo, "[|clnp]")); return (1); } #define ESIS_PDU_REDIRECT 6 #define ESIS_PDU_ESH 2 #define ESIS_PDU_ISH 4 static const struct tok esis_pdu_values[] = { { ESIS_PDU_REDIRECT, "redirect"}, { ESIS_PDU_ESH, "ESH"}, { ESIS_PDU_ISH, "ISH"}, { 0, NULL } }; struct esis_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t reserved; uint8_t type; uint8_t holdtime[2]; uint8_t cksum[2]; }; static void esis_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr; u_int li,esis_pdu_type,source_address_length, source_address_number; const struct esis_header_t *esis_header; if (!ndo->ndo_eflag) ND_PRINT((ndo, "ES-IS")); if (length <= 2) { ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!")); return; } esis_header = (const struct esis_header_t *) pptr; ND_TCHECK(*esis_header); li = esis_header->length_indicator; optr = pptr; /* * Sanity checking of the header. */ if (esis_header->nlpid != NLPID_ESIS) { ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid)); return; } if (esis_header->version != ESIS_VERSION) { ND_PRINT((ndo, " version %d packet not supported", esis_header->version)); return; } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return; } if (li < sizeof(struct esis_header_t) + 2) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return; } esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s, length %u", ndo->ndo_eflag ? "" : ", ", tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type), length)); return; } else ND_PRINT((ndo, "%slength %u\n\t%s (%u)", ndo->ndo_eflag ? "" : ", ", length, tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type), esis_pdu_type)); ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" )); ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum))); osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li); ND_PRINT((ndo, ", holding time: %us, length indicator: %u", EXTRACT_16BITS(esis_header->holdtime), li)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t)); pptr += sizeof(struct esis_header_t); li -= sizeof(struct esis_header_t); switch (esis_pdu_type) { case ESIS_PDU_REDIRECT: { const uint8_t *dst, *snpa, *neta; u_int dstl, snpal, netal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } dstl = *pptr; pptr++; li--; ND_TCHECK2(*pptr, dstl); if (li < dstl) { ND_PRINT((ndo, ", bad redirect/li")); return; } dst = pptr; pptr += dstl; li -= dstl; ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl))); ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpal = *pptr; pptr++; li--; ND_TCHECK2(*pptr, snpal); if (li < snpal) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpa = pptr; pptr += snpal; li -= snpal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } netal = *pptr; pptr++; ND_TCHECK2(*pptr, netal); if (li < netal) { ND_PRINT((ndo, ", bad redirect/li")); return; } neta = pptr; pptr += netal; li -= netal; if (netal == 0) ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa))); else ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal))); break; } case ESIS_PDU_ESH: ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_number = *pptr; pptr++; li--; ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number)); while (source_address_number > 0) { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad esh/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; source_address_number--; } break; case ESIS_PDU_ISH: { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad ish/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad ish/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; break; } default: if (ndo->ndo_vflag <= 1) { if (pptr < ndo->ndo_snapend) print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr); } return; } /* now walk the options */ while (li != 0) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return; } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return; } li -= opli; tptr = pptr; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(esis_option_values,"Unknown",op), op, opli)); switch (op) { case ESIS_OPTION_ES_CONF_TIME: if (opli == 2) { ND_TCHECK2(*pptr, 2); ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr))); } else ND_PRINT((ndo, "(bad length)")); break; case ESIS_OPTION_PROTOCOLS: while (opli>0) { ND_TCHECK(*pptr); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (opli>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; opli--; } break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ case ESIS_OPTION_QOS_MAINTENANCE: case ESIS_OPTION_SECURITY: case ESIS_OPTION_PRIORITY: case ESIS_OPTION_ADDRESS_MASK: case ESIS_OPTION_SNPA_MASK: default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } trunc: return; } static void isis_print_mcid(netdissect_options *ndo, const struct isis_spb_mcid *mcid) { int i; ND_TCHECK(*mcid); ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id)); if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend)) goto trunc; ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl))); ND_PRINT((ndo, ", Digest: ")); for(i=0;i<16;i++) ND_PRINT((ndo, "%.2x ", mcid->digest[i])); trunc: ND_PRINT((ndo, "%s", tstr)); } static int isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN); subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + sizeof(struct isis_subtlv_spb_mcid); len = len - sizeof(struct isis_subtlv_spb_mcid); break; } case ISIS_SUBTLV_SPB_DIGEST: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN); ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { ND_TCHECK2(*(tptr), stlv_len); while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN); ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static int isis_print_mt_capability_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len, tmp; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); len = len - 2; switch (stlv_type) { case ISIS_SUBTLV_SPB_INSTANCE: ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN); ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr))); tptr = tptr + 2; ND_PRINT((ndo, "\n\t RES: %d", EXTRACT_16BITS(tptr) >> 5)); ND_PRINT((ndo, ", V: %d", (EXTRACT_16BITS(tptr) >> 4) & 0x0001)); ND_PRINT((ndo, ", SPSource-ID: %d", (EXTRACT_32BITS(tptr) & 0x000fffff))); tptr = tptr+4; ND_PRINT((ndo, ", No of Trees: %x", *(tptr))); tmp = *(tptr++); len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; while (tmp) { ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN); ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d", *(tptr) >> 7, (*(tptr) >> 6) & 0x01, (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f))); tptr++; ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr + 4; ND_PRINT((ndo, ", BVID: %d, SPVID: %d", (EXTRACT_24BITS(tptr) >> 12) & 0x000fff, EXTRACT_24BITS(tptr) & 0x000fff)); tptr = tptr + 3; len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; tmp--; } break; case ISIS_SUBTLV_SPBM_SI: ND_TCHECK2(*tptr, 8); ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr))); tptr = tptr+2; ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12, (EXTRACT_16BITS(tptr)) & 0x0fff)); tptr = tptr+2; len = len - 8; stlv_len = stlv_len - 8; while (stlv_len >= 4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d", (EXTRACT_32BITS(tptr) >> 31), (EXTRACT_32BITS(tptr) >> 30) & 0x01, (EXTRACT_32BITS(tptr) >> 24) & 0x03f, (EXTRACT_32BITS(tptr)) & 0x0ffffff)); tptr = tptr + 4; len = len - 4; stlv_len = stlv_len - 4; } break; default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } /* shared routine for printing system, node and lsp-ids */ static char * isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } /* print the 4-byte metric block which is common found in the old-style TLVs */ static int isis_print_metric_block(netdissect_options *ndo, const struct isis_metric_block *isis_metric_block) { ND_PRINT((ndo, ", Default Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay)) ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense)) ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error)) ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal")); return(1); /* everything is ok */ } static int isis_print_tlv_ip_reach(netdissect_options *ndo, const uint8_t *cp, const char *ident, int length) { int prefix_len; const struct isis_tlv_ip_reach *tlv_ip_reach; tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp; while (length > 0) { if ((size_t)length < sizeof(*tlv_ip_reach)) { ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)", length, (unsigned long)sizeof(*tlv_ip_reach))); return (0); } if (!ND_TTEST(*tlv_ip_reach)) return (0); prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask)); if (prefix_len == -1) ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), ipaddr_string(ndo, (tlv_ip_reach->mask)))); else ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), prefix_len)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s", ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up", ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay)) ND_PRINT((ndo, "%s Delay Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense)) ND_PRINT((ndo, "%s Expense Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error)) ND_PRINT((ndo, "%s Error Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal")); length -= sizeof(struct isis_tlv_ip_reach); tlv_ip_reach++; } return (1); } /* * this is the common IP-REACH subTLV decoder it is called * from various EXTD-IP REACH TLVs (135,235,236,237) */ static int isis_print_ip_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, int subt, int subl, const char *ident) { /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr,subl); switch(subt) { case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */ case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32: while (subl >= 4) { ND_PRINT((ndo, ", 0x%08x (=%u)", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr))); tptr+=4; subl-=4; } break; case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64: while (subl >= 8) { ND_PRINT((ndo, ", 0x%08x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr+4))); tptr+=8; subl-=8; } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: ND_PRINT((ndo, "%s", ident)); ND_PRINT((ndo, "%s", tstr)); return(0); } /* * this is the common IS-REACH subTLV decoder it is called * from isis_print_ext_is_reach() */ static int isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } /* * this is the common IS-REACH decoder it is called * from various EXTD-IS REACH style TLVs (22,24,222) */ static int isis_print_ext_is_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, int tlv_type) { char ident_buffer[20]; int subtlv_type,subtlv_len,subtlv_sum_len; int proc_bytes = 0; /* how many bytes did we process ? */ if (!ND_TTEST2(*tptr, NODE_ID_LEN)) return(0); ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */ if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */ return(0); ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr))); tptr+=3; } if (!ND_TTEST2(*tptr, 1)) return(0); subtlv_sum_len=*(tptr++); /* read out subTLV length */ proc_bytes=NODE_ID_LEN+3+1; ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no ")); if (subtlv_sum_len) { ND_PRINT((ndo, " (%u)", subtlv_sum_len)); while (subtlv_sum_len>0) { if (!ND_TTEST2(*tptr,2)) return(0); subtlv_type=*(tptr++); subtlv_len=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer)) return(0); tptr+=subtlv_len; subtlv_sum_len-=(subtlv_len+2); proc_bytes+=(subtlv_len+2); } } return(proc_bytes); } /* * this is the common Multi Topology ID decoder * it is called from various MT-TLVs (222,229,235,237) */ static int isis_print_mtid(netdissect_options *ndo, const uint8_t *tptr, const char *ident) { if (!ND_TTEST2(*tptr, 2)) return(0); ND_PRINT((ndo, "%s%s", ident, tok2str(isis_mt_values, "Reserved for IETF Consensus", ISIS_MASK_MTID(EXTRACT_16BITS(tptr))))); ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]", ISIS_MASK_MTID(EXTRACT_16BITS(tptr)), bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr))))); return(2); } /* * this is the common extended IP reach decoder * it is called from TLVs (135,235,236,237) * we process the TLV and optional subTLVs and return * the amount of processed bytes */ static int isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } /* * Clear checksum and lifetime prior to signature verification. */ static void isis_clear_checksum_lifetime(void *header) { struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header; header_lsp->checksum[0] = 0; header_lsp->checksum[1] = 0; header_lsp->remaining_lifetime[0] = 0; header_lsp->remaining_lifetime[1] = 0; } /* * isis_print * Decode IS-IS packets. Return 0 on error. */ static int isis_print(netdissect_options *ndo, const uint8_t *p, u_int length) { const struct isis_common_header *isis_header; const struct isis_iih_lan_header *header_iih_lan; const struct isis_iih_ptp_header *header_iih_ptp; const struct isis_lsp_header *header_lsp; const struct isis_csnp_header *header_csnp; const struct isis_psnp_header *header_psnp; const struct isis_tlv_lsp *tlv_lsp; const struct isis_tlv_ptp_adj *tlv_ptp_adj; const struct isis_tlv_is_reach *tlv_is_reach; const struct isis_tlv_es_reach *tlv_es_reach; uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len; uint8_t ext_is_len, ext_ip_len, mt_len; const uint8_t *optr, *pptr, *tptr; u_short packet_len,pdu_len, key_id; u_int i,vendor_id; int sigcheck; packet_len=length; optr = p; /* initialize the _o_riginal pointer to the packet start - need it for parsing the checksum TLV and authentication TLV verification */ isis_header = (const struct isis_common_header *)p; ND_TCHECK(*isis_header); if (length < ISIS_COMMON_HEADER_SIZE) goto trunc; pptr = p+(ISIS_COMMON_HEADER_SIZE); header_iih_lan = (const struct isis_iih_lan_header *)pptr; header_iih_ptp = (const struct isis_iih_ptp_header *)pptr; header_lsp = (const struct isis_lsp_header *)pptr; header_csnp = (const struct isis_csnp_header *)pptr; header_psnp = (const struct isis_psnp_header *)pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "IS-IS")); /* * Sanity checking of the header. */ if (isis_header->version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->version)); return (0); } if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) { ND_PRINT((ndo, "system ID length of %d is not supported", isis_header->id_length)); return (0); } if (isis_header->pdu_version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version)); return (0); } if (length < isis_header->fixed_len) { ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length)); return (0); } if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) { ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE)); return (0); } max_area = isis_header->max_area; switch(max_area) { case 0: max_area = 3; /* silly shit */ break; case 255: ND_PRINT((ndo, "bad packet -- 255 areas")); return (0); default: break; } id_length = isis_header->id_length; switch(id_length) { case 0: id_length = 6; /* silly shit again */ break; case 1: /* 1-8 are valid sys-ID lenghts */ case 2: case 3: case 4: case 5: case 6: case 7: case 8: break; case 255: id_length = 0; /* entirely useless */ break; default: break; } /* toss any non 6-byte sys-ID len PDUs */ if (id_length != 6 ) { ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length)); return (0); } pdu_type=isis_header->pdu_type; /* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/ if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, "%s%s", ndo->ndo_eflag ? "" : ", ", tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type))); } else { /* ok they seem to want to know everything - lets fully decode it */ ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)", tok2str(isis_pdu_values, "unknown, type %u", pdu_type), isis_header->fixed_len, isis_header->version, isis_header->pdu_version, id_length, isis_header->id_length, max_area, isis_header->max_area)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */ return (0); /* for optionally debugging the common header */ } } switch (pdu_type) { case ISIS_PDU_L1_LAN_IIH: case ISIS_PDU_L2_LAN_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_lan); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", lan-id %s, prio %u", isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN), header_iih_lan->priority)); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_lan->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_lan->circuit_type))); ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u", isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN), (header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); break; case ISIS_PDU_PTP_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_ptp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_ptp->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_ptp->circuit_type))); ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u", header_iih_ptp->circuit_id, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); break; case ISIS_PDU_L1_LSP: case ISIS_PDU_L2_LSP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE)); return (0); } ND_TCHECK(*header_lsp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_lsp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime), EXTRACT_16BITS(header_lsp->checksum))); osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id, EXTRACT_16BITS(header_lsp->checksum), 12, length-12); ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s", pdu_len, ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : "")); if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) { ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : "")); ND_PRINT((ndo, "ATT bit set, ")); } ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : "")); ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)", ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock)))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); break; case ISIS_PDU_L1_CSNP: case ISIS_PDU_L2_CSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_csnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_csnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_csnp->source_id, NODE_ID_LEN), pdu_len)); ND_PRINT((ndo, "\n\t start lsp-id: %s", isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN))); ND_PRINT((ndo, "\n\t end lsp-id: %s", isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); break; case ISIS_PDU_L1_PSNP: case ISIS_PDU_L2_PSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) { ND_PRINT((ndo, "- bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_psnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_psnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_psnp->source_id, NODE_ID_LEN), pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); break; default: if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", length %u", length)); return (1); } (void)print_unknown_data(ndo, pptr, "\n\t ", length); return (0); } /* * Now print the TLV's. */ while (packet_len > 0) { ND_TCHECK2(*pptr, 2); if (packet_len < 2) goto trunc; tlv_type = *pptr++; tlv_len = *pptr++; tmp =tlv_len; /* copy temporary len & pointer to packet data */ tptr = pptr; packet_len -= 2; /* first lets see if we know the TLVs name*/ ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u", tok2str(isis_tlv_values, "unknown", tlv_type), tlv_type, tlv_len)); if (tlv_len == 0) /* something is invalid */ continue; if (packet_len < tlv_len) goto trunc; /* now check if we have a decoder otherwise do a hexdump at the end*/ switch (tlv_type) { case ISIS_TLV_AREA_ADDR: ND_TCHECK2(*tptr, 1); alen = *tptr++; while (tmp && alen < tmp) { ND_TCHECK2(*tptr, alen); ND_PRINT((ndo, "\n\t Area address (length: %u): %s", alen, isonsap_string(ndo, tptr, alen))); tptr += alen; tmp -= alen + 1; if (tmp==0) /* if this is the last area address do not attemt a boundary check */ break; ND_TCHECK2(*tptr, 1); alen = *tptr++; } break; case ISIS_TLV_ISNEIGH: while (tmp >= ETHER_ADDR_LEN) { ND_TCHECK2(*tptr, ETHER_ADDR_LEN); ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN))); tmp -= ETHER_ADDR_LEN; tptr += ETHER_ADDR_LEN; } break; case ISIS_TLV_ISNEIGH_VARLEN: if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */ goto trunctlv; lan_alen = *tptr++; /* LAN address length */ if (lan_alen == 0) { ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)")); break; } tmp --; ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen)); while (tmp >= lan_alen) { ND_TCHECK2(*tptr, lan_alen); ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen))); tmp -= lan_alen; tptr +=lan_alen; } break; case ISIS_TLV_PADDING: break; case ISIS_TLV_MT_IS_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; while (tmp >= 2+NODE_ID_LEN+3+1) { ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_ALIAS_ID: while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_EXT_IS_REACH: while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_REACH: ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */ ND_PRINT((ndo, "\n\t %s", tok2str(isis_is_reach_virtual_values, "bogus virtual flag 0x%02x", *tptr++))); tlv_is_reach = (const struct isis_tlv_is_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_is_reach)) { ND_TCHECK(*tlv_is_reach); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN))); isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_is_reach); tlv_is_reach++; } break; case ISIS_TLV_ESNEIGH: tlv_es_reach = (const struct isis_tlv_es_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_es_reach)) { ND_TCHECK(*tlv_es_reach); ND_PRINT((ndo, "\n\t ES Neighbor: %s", isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN))); isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_es_reach); tlv_es_reach++; } break; /* those two TLVs share the same format */ case ISIS_TLV_INT_IP_REACH: case ISIS_TLV_EXT_IP_REACH: if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len)) return (1); break; case ISIS_TLV_EXTD_IP_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP6_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6ADDR: while (tmp>=sizeof(struct in6_addr)) { ND_TCHECK2(*tptr, sizeof(struct in6_addr)); ND_PRINT((ndo, "\n\t IPv6 interface address: %s", ip6addr_string(ndo, tptr))); tptr += sizeof(struct in6_addr); tmp -= sizeof(struct in6_addr); } break; case ISIS_TLV_AUTH: ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t %s: ", tok2str(isis_subtlv_auth_values, "unknown Authentication type 0x%02x", *tptr))); switch (*tptr) { case ISIS_SUBTLV_AUTH_SIMPLE: if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_SUBTLV_AUTH_MD5: for(i=1;i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1) ND_PRINT((ndo, ", (invalid subTLV) ")); sigcheck = signature_verify(ndo, optr, length, tptr + 1, isis_clear_checksum_lifetime, header_lsp); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); break; case ISIS_SUBTLV_AUTH_GENERIC: ND_TCHECK2(*(tptr + 1), 2); key_id = EXTRACT_16BITS((tptr+1)); ND_PRINT((ndo, "%u, password: ", key_id)); for(i=1 + sizeof(uint16_t);i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } break; case ISIS_SUBTLV_AUTH_PRIVATE: default: if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_PTP_ADJ: tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr; if(tmp>=1) { ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)", tok2str(isis_ptp_adjancey_values, "unknown", *tptr), *tptr)); tmp--; } if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id); ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id))); tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id); } if(tmp>=SYSTEM_ID_LEN) { ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t Neighbor System-ID: %s", isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN))); tmp-=SYSTEM_ID_LEN; } if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id); ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id))); } break; case ISIS_TLV_PROTOCOLS: ND_PRINT((ndo, "\n\t NLPID(s): ")); while (tmp>0) { ND_TCHECK2(*(tptr), 1); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (tmp>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; tmp--; } break; case ISIS_TLV_MT_PORT_CAP: { ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d", (EXTRACT_16BITS (tptr) >> 12), (EXTRACT_16BITS (tptr) & 0x0fff))); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_port_cap_subtlv(ndo, tptr, tmp); break; } case ISIS_TLV_MT_CAPABILITY: ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d", (EXTRACT_16BITS(tptr) >> 15) & 0x01, (EXTRACT_16BITS(tptr) >> 12) & 0x07, EXTRACT_16BITS(tptr) & 0x0fff)); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_capability_subtlv(ndo, tptr, tmp); break; case ISIS_TLV_TE_ROUTER_ID: ND_TCHECK2(*pptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr))); break; case ISIS_TLV_IPADDR: while (tmp>=sizeof(struct in_addr)) { ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr += sizeof(struct in_addr); tmp -= sizeof(struct in_addr); } break; case ISIS_TLV_HOSTNAME: ND_PRINT((ndo, "\n\t Hostname: ")); if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_TLV_SHARED_RISK_GROUP: if (tmp < NODE_ID_LEN) break; ND_TCHECK2(*tptr, NODE_ID_LEN); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); tmp-=(NODE_ID_LEN); if (tmp < 1) break; ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered")); tmp--; if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); while (tmp>=4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr))); tptr+=4; tmp-=4; } break; case ISIS_TLV_LSP: tlv_lsp = (const struct isis_tlv_lsp *)tptr; while(tmp>=sizeof(struct isis_tlv_lsp)) { ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]); ND_PRINT((ndo, "\n\t lsp-id: %s", isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN))); ND_TCHECK2(tlv_lsp->sequence_number, 4); ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number))); ND_TCHECK2(tlv_lsp->remaining_lifetime, 2); ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime))); ND_TCHECK2(tlv_lsp->checksum, 2); ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum))); tmp-=sizeof(struct isis_tlv_lsp); tlv_lsp++; } break; case ISIS_TLV_CHECKSUM: if (tmp < ISIS_TLV_CHECKSUM_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN); ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr))); /* do not attempt to verify the checksum if it is zero * most likely a HMAC-MD5 TLV is also present and * to avoid conflicts the checksum TLV is zeroed. * see rfc3358 for details */ osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr, length); break; case ISIS_TLV_POI: if (tlv_len >= SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s", isis_print_id(tptr + 1, SYSTEM_ID_LEN))); } if (tlv_len == 2 * SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Received from System-ID: %s", isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN))); } break; case ISIS_TLV_MT_SUPPORTED: if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN) break; while (tmp>1) { /* length can only be a multiple of 2, otherwise there is something broken -> so decode down until length is 1 */ if (tmp!=1) { mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; } else { ND_PRINT((ndo, "\n\t invalid MT-ID")); break; } } break; case ISIS_TLV_RESTART_SIGNALING: /* first attempt to decode the flags */ if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN); ND_PRINT((ndo, "\n\t Flags [%s]", bittok2str(isis_restart_flag_values, "none", *tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; /* is there anything other than the flags field? */ if (tmp == 0) break; if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN); ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; /* is there an additional sysid field present ?*/ if (tmp == SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN))); } break; case ISIS_TLV_IDRP_INFO: if (tmp < ISIS_TLV_IDRP_INFO_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN); ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s", tok2str(isis_subtlv_idrp_values, "Unknown (0x%02x)", *tptr))); switch (*tptr++) { case ISIS_SUBTLV_IDRP_ASN: ND_TCHECK2(*tptr, 2); /* fetch AS number */ ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr))); break; case ISIS_SUBTLV_IDRP_LOCAL: case ISIS_SUBTLV_IDRP_RES: default: if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_LSP_BUFFERSIZE: if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN); ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr))); break; case ISIS_TLV_PART_DIS: while (tmp >= SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN))); tptr+=SYSTEM_ID_LEN; tmp-=SYSTEM_ID_LEN; } break; case ISIS_TLV_PREFIX_NEIGH: if (tmp < sizeof(struct isis_metric_block)) break; ND_TCHECK2(*tptr, sizeof(struct isis_metric_block)); ND_PRINT((ndo, "\n\t Metric Block")); isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr); tptr+=sizeof(struct isis_metric_block); tmp-=sizeof(struct isis_metric_block); while(tmp>0) { ND_TCHECK2(*tptr, 1); prefix_len=*tptr++; /* read out prefix length in semioctets*/ if (prefix_len < 2) { ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len)); break; } tmp--; if (tmp < prefix_len/2) break; ND_TCHECK2(*tptr, prefix_len / 2); ND_PRINT((ndo, "\n\t\tAddress: %s/%u", isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4)); tptr+=prefix_len/2; tmp-=prefix_len/2; } break; case ISIS_TLV_IIH_SEQNR: if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */ ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr))); break; case ISIS_TLV_VENDOR_PRIVATE: if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */ vendor_id = EXTRACT_24BITS(tptr); ND_PRINT((ndo, "\n\t Vendor: %s (%u)", tok2str(oui_values, "Unknown", vendor_id), vendor_id)); tptr+=3; tmp-=3; if (tmp > 0) /* hexdump the rest */ if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp)) return(0); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case ISIS_TLV_DECNET_PHASE4: case ISIS_TLV_LUCENT_PRIVATE: case ISIS_TLV_IPAUTH: case ISIS_TLV_NORTEL_PRIVATE1: case ISIS_TLV_NORTEL_PRIVATE2: default: if (ndo->ndo_vflag <= 1) { if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len)) return(0); } break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len)) return(0); } pptr += tlv_len; packet_len -= tlv_len; } if (packet_len != 0) { ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len)); } return (1); trunc: ND_PRINT((ndo, "%s", tstr)); return (1); trunctlv: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static void osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length) { uint16_t calculated_checksum; /* do not attempt to verify the checksum if it is zero, * if the offset is nonsense, * or the base pointer is not sane */ if (!checksum || checksum_offset < 0 || !ND_TTEST2(*(pptr + checksum_offset), 2) || (u_int)checksum_offset > length || !ND_TTEST2(*pptr, length)) { ND_PRINT((ndo, " (unverified)")); } else { #if 0 printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length); #endif calculated_checksum = create_osi_cksum(pptr, checksum_offset, length); if (checksum == calculated_checksum) { ND_PRINT((ndo, " (correct)")); } else { ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum)); } } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2671_0
crossvul-cpp_data_bad_3358_1
/* * IPv6 output functions * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on linux/net/ipv4/ip_output.c * * 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. * * Changes: * A.N.Kuznetsov : airthmetics in fragmentation. * extension headers are implemented. * route changes now work. * ip6_forward does not confuse sniffers. * etc. * * H. von Brand : Added missing #include <linux/string.h> * Imran Patel : frag id should be in NBO * Kazunori MIYAZAWA @USAGI * : add ip6_append_data and related functions * for datagram xmit */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/route.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/bpf-cgroup.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/rawv6.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/checksum.h> #include <linux/mroute6.h> #include <net/l3mdev.h> #include <net/lwtunnel.h> static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; struct in6_addr *nexthop; int ret; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) && ((mroute6_socket(net, skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, newskb, NULL, newskb->dev, dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len); if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <= IPV6_ADDR_SCOPE_NODELOCAL && !(dev->flags & IFF_LOOPBACK)) { kfree_skb(skb); return 0; } } if (lwtunnel_xmit_redirect(dst->lwtstate)) { int res = lwtunnel_xmit(skb); if (res < 0 || res == LWTUNNEL_XMIT_DONE) return res; } rcu_read_lock_bh(); nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr); neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop); if (unlikely(!neigh)) neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false); if (!IS_ERR(neigh)) { sock_confirm_neigh(skb, neigh); ret = neigh_output(neigh, skb); rcu_read_unlock_bh(); return ret; } rcu_read_unlock_bh(); IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb) { int ret; ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb); if (ret) { kfree_skb(skb); return ret; } if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) || dst_allfrag(skb_dst(skb)) || (IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size)) return ip6_fragment(net, sk, skb, ip6_finish_output2); else return ip6_finish_output2(net, sk, skb); } int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (unlikely(idev->cnf.disable_ipv6)) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb, NULL, dev, ip6_finish_output, !(IP6CB(skb)->flags & IP6SKB_REROUTED)); } /* * xmit an sk_buff (used by TCP, SCTP and DCCP) * Note : socket lock is not held for SYNACK packets, but might be modified * by calls to skb_set_owner_w() and ipv6_local_error(), * which are using proper atomic operations or spinlocks. */ int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, __u32 mark, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (!skb2) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } consume_skb(skb); skb = skb2; /* skb_set_owner_w() changes sk->sk_wmem_alloc atomically, * it is safe to call in our context (socket lock not held) */ skb_set_owner_w(skb, (struct sock *)sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop, &fl6->saddr); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->protocol = htons(ETH_P_IPV6); skb->priority = sk->sk_priority; skb->mark = mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); /* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */ skb = l3mdev_ip6_out((struct sock *)sk, skb); if (unlikely(!skb)) return 0; /* hooks should never assume socket lock is held. * we promote our socket to non const */ return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, (struct sock *)sk, skb, NULL, dst->dev, dst_output); } skb->dev = dst->dev; /* ipv6_local_error() does not require socket lock, * we promote our socket to non const */ ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } EXPORT_SYMBOL(ip6_xmit); static int ip6_call_ra_chain(struct sk_buff *skb, int sel) { struct ip6_ra_chain *ra; struct sock *last = NULL; read_lock(&ip6_ra_lock); for (ra = ip6_ra_chain; ra; ra = ra->next) { struct sock *sk = ra->sk; if (sk && ra->sel == sel && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == skb->dev->ifindex)) { if (last) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) rawv6_rcv(last, skb2); } last = sk; } } if (last) { rawv6_rcv(last, skb); read_unlock(&ip6_ra_lock); return 1; } read_unlock(&ip6_ra_lock); return 0; } static int ip6_forward_proxy_check(struct sk_buff *skb) { struct ipv6hdr *hdr = ipv6_hdr(skb); u8 nexthdr = hdr->nexthdr; __be16 frag_off; int offset; if (ipv6_ext_hdr(nexthdr)) { offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off); if (offset < 0) return 0; } else offset = sizeof(struct ipv6hdr); if (nexthdr == IPPROTO_ICMPV6) { struct icmp6hdr *icmp6; if (!pskb_may_pull(skb, (skb_network_header(skb) + offset + 1 - skb->data))) return 0; icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset); switch (icmp6->icmp6_type) { case NDISC_ROUTER_SOLICITATION: case NDISC_ROUTER_ADVERTISEMENT: case NDISC_NEIGHBOUR_SOLICITATION: case NDISC_NEIGHBOUR_ADVERTISEMENT: case NDISC_REDIRECT: /* For reaction involving unicast neighbor discovery * message destined to the proxied address, pass it to * input function. */ return 1; default: break; } } /* * The proxying router can't forward traffic sent to a link-local * address, so signal the sender and discard the packet. This * behavior is clarified by the MIPv6 specification. */ if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) { dst_link_failure(skb); return -1; } return 0; } static inline int ip6_forward_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { return dst_output(net, sk, skb); } static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst) { unsigned int mtu; struct inet6_dev *idev; if (dst_metric_locked(dst, RTAX_MTU)) { mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; } mtu = IPV6_MIN_MTU; rcu_read_lock(); idev = __in6_dev_get(dst->dev); if (idev) mtu = idev->cnf.mtu6; rcu_read_unlock(); return mtu; } static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; /* ipv6 conntrack defrag sets max_frag_size + ignore_df */ if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu) return true; if (skb->ignore_df) return false; if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu)) return false; return true; } int ip6_forward(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr = ipv6_hdr(skb); struct inet6_skb_parm *opt = IP6CB(skb); struct net *net = dev_net(dst->dev); u32 mtu; if (net->ipv6.devconf_all->forwarding == 0) goto error; if (skb->pkt_type != PACKET_HOST) goto drop; if (unlikely(skb->sk)) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } skb_forward_csum(skb); /* * We DO NOT make any processing on * RA packets, pushing them to user level AS IS * without ane WARRANTY that application will be able * to interpret them. The reason is that we * cannot make anything clever here. * * We are not end-node, so that if packet contains * AH/ESP, we cannot make anything. * Defragmentation also would be mistake, RA packets * cannot be fragmented, because there is no warranty * that different fragments will go along one path. --ANK */ if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) { if (ip6_call_ra_chain(skb, ntohs(opt->ra))) return 0; } /* * check and decrement ttl */ if (hdr->hop_limit <= 1) { /* Force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS); kfree_skb(skb); return -ETIMEDOUT; } /* XXX: idev->cnf.proxy_ndp? */ if (net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) { int proxied = ip6_forward_proxy_check(skb); if (proxied > 0) return ip6_input(skb); else if (proxied < 0) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } } if (!xfrm6_route_forward(skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } dst = skb_dst(skb); /* IPv6 specs say nothing about it, but it is clear that we cannot send redirects to source routed frames. We don't send redirects to frames decapsulated from IPsec. */ if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) { struct in6_addr *target = NULL; struct inet_peer *peer; struct rt6_info *rt; /* * incoming and outgoing devices are the same * send a redirect. */ rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) target = &rt->rt6i_gateway; else target = &hdr->daddr; peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1); /* Limit redirects both by destination (here) and by source (inside ndisc_send_redirect) */ if (inet_peer_xrlim_allow(peer, 1*HZ)) ndisc_send_redirect(skb, target); if (peer) inet_putpeer(peer); } else { int addrtype = ipv6_addr_type(&hdr->saddr); /* This check is security critical. */ if (addrtype == IPV6_ADDR_ANY || addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK)) goto error; if (addrtype & IPV6_ADDR_LINKLOCAL) { icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_NOT_NEIGHBOUR, 0); goto error; } } mtu = ip6_dst_mtu_forward(dst); if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (ip6_pkt_too_big(skb, mtu)) { /* Again, force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (skb_cow(skb, dst->dev->hard_header_len)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS); goto drop; } hdr = ipv6_hdr(skb); /* Mangling hops number delayed to point after skb COW */ hdr->hop_limit--; __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS); __IP6_ADD_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, net, NULL, skb, skb->dev, dst->dev, ip6_forward_finish); error: __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS); drop: kfree_skb(skb); return -EINVAL; } static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); } int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb, int (*output)(struct net *, struct sock *, struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id; int ptr, offset = 0, err = 0; u8 *prevhdr, nexthdr = 0; hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (unlikely(!skb->ignore_df && skb->len > mtu)) goto fail_toobig; if (IP6CB(skb)->frag_max_size) { if (IP6CB(skb)->frag_max_size > mtu) goto fail_toobig; /* don't send fragments larger than what we received */ mtu = IP6CB(skb)->frag_max_size; if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } if (mtu < hlen + sizeof(struct frag_hdr) + 8) goto fail_toobig; mtu -= hlen + sizeof(struct frag_hdr); frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr); if (skb->ip_summed == CHECKSUM_PARTIAL && (err = skb_checksum_help(skb))) goto fail; hroom = LL_RESERVED_SPACE(rt->dst.dev); if (skb_has_frag_list(skb)) { unsigned int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb) || skb_headroom(skb) < (hroom + sizeof(struct frag_hdr))) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr))) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); __skb_pull(skb, hlen); fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); fh->identification = frag_id; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(net, sk, skb); if (!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); ip6_rt_put(rt); return 0; } kfree_skb_list(frag); IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); ip6_rt_put(rt); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while (left > 0) { u8 *fragnexthdr_offset; len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* Allocate buffer */ frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC); if (!frag) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); fragnexthdr_offset = skb_network_header(frag); fragnexthdr_offset += prevhdr - skb_network_header(skb); *fragnexthdr_offset = NEXTHDR_FRAGMENT; /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; fh->identification = frag_id; /* * Copy a block of the IP datagram. */ BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag), len)); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(net, sk, frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); consume_skb(skb); return err; fail_toobig: if (skb->sk && dst_allfrag(skb_dst(skb))) sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK); skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); err = -EMSGSIZE; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } static inline int ip6_rt_check(const struct rt6key *rt_key, const struct in6_addr *fl_addr, const struct in6_addr *addr_cache) { return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) && (!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache)); } static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (!(fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF) && (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex))) { dst_release(dst); dst = NULL; } out: return dst; } static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD struct neighbour *n; struct rt6_info *rt; #endif int err; int flags = 0; /* The correct way to handle this would be to do * ip6_route_get_saddr, and then ip6_route_output; however, * the route-specific preferred source forces the * ip6_route_output call _before_ ip6_route_get_saddr. * * In source specific routing (no src=any default route), * ip6_route_output will fail given src=any saddr, though, so * that's why we try it again later. */ if (ipv6_addr_any(&fl6->saddr) && (!*dst || !(*dst)->error)) { struct rt6_info *rt; bool had_dst = *dst != NULL; if (!had_dst) *dst = ip6_route_output(net, sk, fl6); rt = (*dst)->error ? NULL : (struct rt6_info *)*dst; err = ip6_route_get_saddr(net, rt, &fl6->daddr, sk ? inet6_sk(sk)->srcprefs : 0, &fl6->saddr); if (err) goto out_err_release; /* If we had an erroneous initial result, pretend it * never existed and let the SA-enabled version take * over. */ if (!had_dst && (*dst)->error) { dst_release(*dst); *dst = NULL; } if (fl6->flowi6_oif) flags |= RT6_LOOKUP_F_IFACE; } if (!*dst) *dst = ip6_route_output_flags(net, sk, fl6, flags); err = (*dst)->error; if (err) goto out_err_release; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * Here if the dst entry we've looked up * has a neighbour entry that is in the INCOMPLETE * state and the src address from the flow is * marked as OPTIMISTIC, we release the found * dst entry and replace it instead with the * dst entry of the nexthop router */ rt = (struct rt6_info *) *dst; rcu_read_lock_bh(); n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr)); err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0; rcu_read_unlock_bh(); if (err) { struct inet6_ifaddr *ifp; struct flowi6 fl_gw6; int redirect; ifp = ipv6_get_ifaddr(net, &fl6->saddr, (*dst)->dev, 1); redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC); if (ifp) in6_ifa_put(ifp); if (redirect) { /* * We need to get the dst entry for the * default router instead */ dst_release(*dst); memcpy(&fl_gw6, fl6, sizeof(struct flowi6)); memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr)); *dst = ip6_route_output(net, sk, &fl_gw6); err = (*dst)->error; if (err) goto out_err_release; } } #endif if (ipv6_addr_v4mapped(&fl6->saddr) && !(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) { err = -EAFNOSUPPORT; goto out_err_release; } return 0; out_err_release: dst_release(*dst); *dst = NULL; if (err == -ENETUNREACH) IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES); return err; } /** * ip6_dst_lookup - perform route lookup on flow * @sk: socket which provides route info * @dst: pointer to dst_entry * for result * @fl6: flow to lookup * * This function performs a route lookup on the given flow. * * It returns zero on success, or a standard errno code on error. */ int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { *dst = NULL; return ip6_dst_lookup_tail(net, sk, dst, fl6); } EXPORT_SYMBOL_GPL(ip6_dst_lookup); /** * ip6_dst_lookup_flow - perform route lookup on flow with ipsec * @sk: socket which provides route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_dst_lookup_flow(const struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sock_net(sk), sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); /** * ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. * It will take the socket dst lock when operating on the dst cache. * As a result, this function can only be used in process context. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); dst = ip6_sk_dst_check(sk, dst, fl6); if (!dst) dst = ip6_dst_lookup_flow(sk, fl6, final_dst); return dst; } EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow); static inline int ip6_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int exthdrlen, int transhdrlen, int mtu, unsigned int flags, const struct flowi6 *fl6) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ skb = skb_peek_tail(queue); if (!skb) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (!skb) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_set_network_header(skb, exthdrlen); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->csum = 0; if (flags & MSG_CONFIRM) skb_set_dst_pending_confirm(skb, 1); __skb_queue_tail(queue, skb); } else if (skb_is_gso(skb)) { goto append; } skb->ip_summed = CHECKSUM_PARTIAL; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; skb_shinfo(skb)->ip6_frag_id = ipv6_select_ident(sock_net(sk), &fl6->daddr, &fl6->saddr); append: return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, unsigned int orig_mtu) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (!skb) { /* first fragment, reserve header_len */ *mtu = orig_mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = orig_mtu; } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork, struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6, struct rt6_info *rt, struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); unsigned int mtu; struct ipv6_txoptions *opt = ipc6->opt; /* * setup for corking */ if (opt) { if (WARN_ON(v6_cork->opt)) return -EINVAL; v6_cork->opt = kzalloc(opt->tot_len, sk->sk_allocation); if (unlikely(!v6_cork->opt)) return -ENOBUFS; v6_cork->opt->tot_len = opt->tot_len; v6_cork->opt->opt_flen = opt->opt_flen; v6_cork->opt->opt_nflen = opt->opt_nflen; v6_cork->opt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation); if (opt->dst0opt && !v6_cork->opt->dst0opt) return -ENOBUFS; v6_cork->opt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation); if (opt->dst1opt && !v6_cork->opt->dst1opt) return -ENOBUFS; v6_cork->opt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation); if (opt->hopopt && !v6_cork->opt->hopopt) return -ENOBUFS; v6_cork->opt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation); if (opt->srcrt && !v6_cork->opt->srcrt) return -ENOBUFS; /* need source address above miyazawa*/ } dst_hold(&rt->dst); cork->base.dst = &rt->dst; cork->fl.u.ip6 = *fl6; v6_cork->hop_limit = ipc6->hlimit; v6_cork->tclass = ipc6->tclass; if (rt->dst.flags & DST_XFRM_TUNNEL) mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(&rt->dst); else mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(rt->dst.path); if (np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } cork->base.fragsize = mtu; if (dst_allfrag(rt->dst.path)) cork->base.flags |= IPCORK_ALLFRAG; cork->base.length = 0; return 0; } static int __ip6_append_data(struct sock *sk, struct flowi6 *fl6, struct sk_buff_head *queue, struct inet_cork *cork, struct inet6_cork *v6_cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags, struct ipcm6_cookie *ipc6, const struct sockcm_cookie *sockc) { struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen = 0; int dst_exthdrlen = 0; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; struct rt6_info *rt = (struct rt6_info *)cork->dst; struct ipv6_txoptions *opt = v6_cork->opt; int csummode = CHECKSUM_NONE; unsigned int maxnonfragsize, headersize; skb = skb_peek_tail(queue); if (!skb) { exthdrlen = opt ? opt->opt_flen : 0; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } mtu = cork->fragsize; orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (cork->length + length > mtu - headersize && ipc6->dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; if (cork->length + length > maxnonfragsize - headersize) { emsgsize: ipv6_local_error(sk, EMSGSIZE, fl6, mtu - headersize + sizeof(struct ipv6hdr)); return -EMSGSIZE; } /* CHECKSUM_PARTIAL only with no extension headers and when * we are not going to fragment */ if (transhdrlen && sk->sk_protocol == IPPROTO_UDP && headersize == sizeof(struct ipv6hdr) && length <= mtu - headersize && !(flags & MSG_MORE) && rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM)) csummode = CHECKSUM_PARTIAL; if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, sockc->tsflags, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ cork->length += length; if ((((length + fragheaderlen) > mtu) || (skb && skb_is_gso(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) && (sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, exthdrlen, transhdrlen, mtu, flags, fl6); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (!skb || !skb_prev) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(!skb)) err = -ENOBUFS; } if (!skb) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; kfree_skb(skb); goto error; } else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; if ((flags & MSG_CONFIRM) && !skb_prev) skb_set_dst_pending_confirm(skb, 1); /* * Put the packet on the pending queue */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; } int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); int exthdrlen; int err; if (flags&MSG_PROBE) return 0; if (skb_queue_empty(&sk->sk_write_queue)) { /* * setup for corking */ err = ip6_setup_cork(sk, &inet->cork, &np->cork, ipc6, rt, fl6); if (err) return err; exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); length += exthdrlen; transhdrlen += exthdrlen; } else { fl6 = &inet->cork.fl.u.ip6; transhdrlen = 0; } return __ip6_append_data(sk, fl6, &sk->sk_write_queue, &inet->cork.base, &np->cork, sk_page_frag(sk), getfrag, from, length, transhdrlen, flags, ipc6, sockc); } EXPORT_SYMBOL_GPL(ip6_append_data); static void ip6_cork_release(struct inet_cork_full *cork, struct inet6_cork *v6_cork) { if (v6_cork->opt) { kfree(v6_cork->opt->dst0opt); kfree(v6_cork->opt->dst1opt); kfree(v6_cork->opt->hopopt); kfree(v6_cork->opt->srcrt); kfree(v6_cork->opt); v6_cork->opt = NULL; } if (cork->base.dst) { dst_release(cork->base.dst); cork->base.dst = NULL; cork->base.flags &= ~IPCORK_ALLFRAG; } memset(&cork->fl, 0, sizeof(cork->fl)); } struct sk_buff *__ip6_make_skb(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = v6_cork->opt; struct rt6_info *rt = (struct rt6_info *)cork->base.dst; struct flowi6 *fl6 = &cork->fl.u.ip6; unsigned char proto = fl6->flowi6_proto; skb = __skb_dequeue(queue); if (!skb) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ skb->ignore_df = ip6_sk_ignore_df(sk); *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, v6_cork->tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->hop_limit = v6_cork->hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } ip6_cork_release(cork, v6_cork); out: return skb; } int ip6_send_skb(struct sk_buff *skb) { struct net *net = sock_net(skb->sk); struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); int err; err = ip6_local_out(net, skb->sk, skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); } return err; } int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; skb = ip6_finish_skb(sk); if (!skb) return 0; return ip6_send_skb(skb); } EXPORT_SYMBOL_GPL(ip6_push_pending_frames); static void __ip6_flush_pending_frames(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(queue)) != NULL) { if (skb_dst(skb)) IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); } ip6_cork_release(cork, v6_cork); } void ip6_flush_pending_frames(struct sock *sk) { __ip6_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork, &inet6_sk(sk)->cork); } EXPORT_SYMBOL_GPL(ip6_flush_pending_frames); struct sk_buff *ip6_make_skb(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_cork_full cork; struct inet6_cork v6_cork; struct sk_buff_head queue; int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.base.flags = 0; cork.base.addr = 0; cork.base.opt = NULL; v6_cork.opt = NULL; err = ip6_setup_cork(sk, &cork, &v6_cork, ipc6, rt, fl6); if (err) return ERR_PTR(err); if (ipc6->dontfrag < 0) ipc6->dontfrag = inet6_sk(sk)->dontfrag; err = __ip6_append_data(sk, fl6, &queue, &cork.base, &v6_cork, &current->task_frag, getfrag, from, length + exthdrlen, transhdrlen + exthdrlen, flags, ipc6, sockc); if (err) { __ip6_flush_pending_frames(sk, &queue, &cork, &v6_cork); return ERR_PTR(err); } return __ip6_make_skb(sk, &queue, &cork, &v6_cork); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3358_1
crossvul-cpp_data_bad_2777_0
/*- * Copyright (c) 2009 Michihiro NAKAJIMA * 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(S) ``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(S) 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 "archive_platform.h" __FBSDID("$FreeBSD$"); #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_LIBXML_XMLREADER_H #include <libxml/xmlreader.h> #elif HAVE_BSDXML_H #include <bsdxml.h> #elif HAVE_EXPAT_H #include <expat.h> #endif #ifdef HAVE_BZLIB_H #include <bzlib.h> #endif #if HAVE_LZMA_H #include <lzma.h> #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #endif #include "archive.h" #include "archive_digest_private.h" #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_private.h" #include "archive_read_private.h" #if (!defined(HAVE_LIBXML_XMLREADER_H) && \ !defined(HAVE_BSDXML_H) && !defined(HAVE_EXPAT_H)) ||\ !defined(HAVE_ZLIB_H) || \ !defined(ARCHIVE_HAS_MD5) || !defined(ARCHIVE_HAS_SHA1) /* * xar needs several external libraries. * o libxml2 or expat --- XML parser * o openssl or MD5/SHA1 hash function * o zlib * o bzlib2 (option) * o liblzma (option) */ int archive_read_support_format_xar(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_xar"); archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Xar not supported on this platform"); return (ARCHIVE_WARN); } #else /* Support xar format */ /* #define DEBUG 1 */ /* #define DEBUG_PRINT_TOC 1 */ #if DEBUG_PRINT_TOC #define PRINT_TOC(d, outbytes) do { \ unsigned char *x = (unsigned char *)(uintptr_t)d; \ unsigned char c = x[outbytes-1]; \ x[outbytes - 1] = 0; \ fprintf(stderr, "%s", x); \ fprintf(stderr, "%c", c); \ x[outbytes - 1] = c; \ } while (0) #else #define PRINT_TOC(d, outbytes) #endif #define HEADER_MAGIC 0x78617221 #define HEADER_SIZE 28 #define HEADER_VERSION 1 #define CKSUM_NONE 0 #define CKSUM_SHA1 1 #define CKSUM_MD5 2 #define MD5_SIZE 16 #define SHA1_SIZE 20 #define MAX_SUM_SIZE 20 enum enctype { NONE, GZIP, BZIP2, LZMA, XZ, }; struct chksumval { int alg; size_t len; unsigned char val[MAX_SUM_SIZE]; }; struct chksumwork { int alg; #ifdef ARCHIVE_HAS_MD5 archive_md5_ctx md5ctx; #endif #ifdef ARCHIVE_HAS_SHA1 archive_sha1_ctx sha1ctx; #endif }; struct xattr { struct xattr *next; struct archive_string name; uint64_t id; uint64_t length; uint64_t offset; uint64_t size; enum enctype encoding; struct chksumval a_sum; struct chksumval e_sum; struct archive_string fstype; }; struct xar_file { struct xar_file *next; struct xar_file *hdnext; struct xar_file *parent; int subdirs; unsigned int has; #define HAS_DATA 0x00001 #define HAS_PATHNAME 0x00002 #define HAS_SYMLINK 0x00004 #define HAS_TIME 0x00008 #define HAS_UID 0x00010 #define HAS_GID 0x00020 #define HAS_MODE 0x00040 #define HAS_TYPE 0x00080 #define HAS_DEV 0x00100 #define HAS_DEVMAJOR 0x00200 #define HAS_DEVMINOR 0x00400 #define HAS_INO 0x00800 #define HAS_FFLAGS 0x01000 #define HAS_XATTR 0x02000 #define HAS_ACL 0x04000 uint64_t id; uint64_t length; uint64_t offset; uint64_t size; enum enctype encoding; struct chksumval a_sum; struct chksumval e_sum; struct archive_string pathname; struct archive_string symlink; time_t ctime; time_t mtime; time_t atime; struct archive_string uname; int64_t uid; struct archive_string gname; int64_t gid; mode_t mode; dev_t dev; dev_t devmajor; dev_t devminor; int64_t ino64; struct archive_string fflags_text; unsigned int link; unsigned int nlink; struct archive_string hardlink; struct xattr *xattr_list; }; struct hdlink { struct hdlink *next; unsigned int id; int cnt; struct xar_file *files; }; struct heap_queue { struct xar_file **files; int allocated; int used; }; enum xmlstatus { INIT, XAR, TOC, TOC_CREATION_TIME, TOC_CHECKSUM, TOC_CHECKSUM_OFFSET, TOC_CHECKSUM_SIZE, TOC_FILE, FILE_DATA, FILE_DATA_LENGTH, FILE_DATA_OFFSET, FILE_DATA_SIZE, FILE_DATA_ENCODING, FILE_DATA_A_CHECKSUM, FILE_DATA_E_CHECKSUM, FILE_DATA_CONTENT, FILE_EA, FILE_EA_LENGTH, FILE_EA_OFFSET, FILE_EA_SIZE, FILE_EA_ENCODING, FILE_EA_A_CHECKSUM, FILE_EA_E_CHECKSUM, FILE_EA_NAME, FILE_EA_FSTYPE, FILE_CTIME, FILE_MTIME, FILE_ATIME, FILE_GROUP, FILE_GID, FILE_USER, FILE_UID, FILE_MODE, FILE_DEVICE, FILE_DEVICE_MAJOR, FILE_DEVICE_MINOR, FILE_DEVICENO, FILE_INODE, FILE_LINK, FILE_TYPE, FILE_NAME, FILE_ACL, FILE_ACL_DEFAULT, FILE_ACL_ACCESS, FILE_ACL_APPLEEXTENDED, /* BSD file flags. */ FILE_FLAGS, FILE_FLAGS_USER_NODUMP, FILE_FLAGS_USER_IMMUTABLE, FILE_FLAGS_USER_APPEND, FILE_FLAGS_USER_OPAQUE, FILE_FLAGS_USER_NOUNLINK, FILE_FLAGS_SYS_ARCHIVED, FILE_FLAGS_SYS_IMMUTABLE, FILE_FLAGS_SYS_APPEND, FILE_FLAGS_SYS_NOUNLINK, FILE_FLAGS_SYS_SNAPSHOT, /* Linux file flags. */ FILE_EXT2, FILE_EXT2_SecureDeletion, FILE_EXT2_Undelete, FILE_EXT2_Compress, FILE_EXT2_Synchronous, FILE_EXT2_Immutable, FILE_EXT2_AppendOnly, FILE_EXT2_NoDump, FILE_EXT2_NoAtime, FILE_EXT2_CompDirty, FILE_EXT2_CompBlock, FILE_EXT2_NoCompBlock, FILE_EXT2_CompError, FILE_EXT2_BTree, FILE_EXT2_HashIndexed, FILE_EXT2_iMagic, FILE_EXT2_Journaled, FILE_EXT2_NoTail, FILE_EXT2_DirSync, FILE_EXT2_TopDir, FILE_EXT2_Reserved, UNKNOWN, }; struct unknown_tag { struct unknown_tag *next; struct archive_string name; }; struct xar { uint64_t offset; /* Current position in the file. */ int64_t total; uint64_t h_base; int end_of_file; #define OUTBUFF_SIZE (1024 * 64) unsigned char *outbuff; enum xmlstatus xmlsts; enum xmlstatus xmlsts_unknown; struct unknown_tag *unknowntags; int base64text; /* * TOC */ uint64_t toc_remaining; uint64_t toc_total; uint64_t toc_chksum_offset; uint64_t toc_chksum_size; /* * For Decoding data. */ enum enctype rd_encoding; z_stream stream; int stream_valid; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) bz_stream bzstream; int bzstream_valid; #endif #if HAVE_LZMA_H && HAVE_LIBLZMA lzma_stream lzstream; int lzstream_valid; #endif /* * For Checksum data. */ struct chksumwork a_sumwrk; struct chksumwork e_sumwrk; struct xar_file *file; /* current reading file. */ struct xattr *xattr; /* current reading extended attribute. */ struct heap_queue file_queue; struct xar_file *hdlink_orgs; struct hdlink *hdlink_list; int entry_init; uint64_t entry_total; uint64_t entry_remaining; size_t entry_unconsumed; uint64_t entry_size; enum enctype entry_encoding; struct chksumval entry_a_sum; struct chksumval entry_e_sum; struct archive_string_conv *sconv; }; struct xmlattr { struct xmlattr *next; char *name; char *value; }; struct xmlattr_list { struct xmlattr *first; struct xmlattr **last; }; static int xar_bid(struct archive_read *, int); static int xar_read_header(struct archive_read *, struct archive_entry *); static int xar_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int xar_read_data_skip(struct archive_read *); static int xar_cleanup(struct archive_read *); static int move_reading_point(struct archive_read *, uint64_t); static int rd_contents_init(struct archive_read *, enum enctype, int, int); static int rd_contents(struct archive_read *, const void **, size_t *, size_t *, uint64_t); static uint64_t atol10(const char *, size_t); static int64_t atol8(const char *, size_t); static size_t atohex(unsigned char *, size_t, const char *, size_t); static time_t parse_time(const char *p, size_t n); static int heap_add_entry(struct archive_read *a, struct heap_queue *, struct xar_file *); static struct xar_file *heap_get_entry(struct heap_queue *); static int add_link(struct archive_read *, struct xar *, struct xar_file *); static void checksum_init(struct archive_read *, int, int); static void checksum_update(struct archive_read *, const void *, size_t, const void *, size_t); static int checksum_final(struct archive_read *, const void *, size_t, const void *, size_t); static void checksum_cleanup(struct archive_read *); static int decompression_init(struct archive_read *, enum enctype); static int decompress(struct archive_read *, const void **, size_t *, const void *, size_t *); static int decompression_cleanup(struct archive_read *); static void xmlattr_cleanup(struct xmlattr_list *); static int file_new(struct archive_read *, struct xar *, struct xmlattr_list *); static void file_free(struct xar_file *); static int xattr_new(struct archive_read *, struct xar *, struct xmlattr_list *); static void xattr_free(struct xattr *); static int getencoding(struct xmlattr_list *); static int getsumalgorithm(struct xmlattr_list *); static int unknowntag_start(struct archive_read *, struct xar *, const char *); static void unknowntag_end(struct xar *, const char *); static int xml_start(struct archive_read *, const char *, struct xmlattr_list *); static void xml_end(void *, const char *); static void xml_data(void *, const char *, int); static int xml_parse_file_flags(struct xar *, const char *); static int xml_parse_file_ext2(struct xar *, const char *); #if defined(HAVE_LIBXML_XMLREADER_H) static int xml2_xmlattr_setup(struct archive_read *, struct xmlattr_list *, xmlTextReaderPtr); static int xml2_read_cb(void *, char *, int); static int xml2_close_cb(void *); static void xml2_error_hdr(void *, const char *, xmlParserSeverities, xmlTextReaderLocatorPtr); static int xml2_read_toc(struct archive_read *); #elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) struct expat_userData { int state; struct archive_read *archive; }; static int expat_xmlattr_setup(struct archive_read *, struct xmlattr_list *, const XML_Char **); static void expat_start_cb(void *, const XML_Char *, const XML_Char **); static void expat_end_cb(void *, const XML_Char *); static void expat_data_cb(void *, const XML_Char *, int); static int expat_read_toc(struct archive_read *); #endif int archive_read_support_format_xar(struct archive *_a) { struct xar *xar; struct archive_read *a = (struct archive_read *)_a; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_xar"); xar = (struct xar *)calloc(1, sizeof(*xar)); if (xar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate xar data"); return (ARCHIVE_FATAL); } r = __archive_read_register_format(a, xar, "xar", xar_bid, NULL, xar_read_header, xar_read_data, xar_read_data_skip, NULL, xar_cleanup, NULL, NULL); if (r != ARCHIVE_OK) free(xar); return (r); } static int xar_bid(struct archive_read *a, int best_bid) { const unsigned char *b; int bid; (void)best_bid; /* UNUSED */ b = __archive_read_ahead(a, HEADER_SIZE, NULL); if (b == NULL) return (-1); bid = 0; /* * Verify magic code */ if (archive_be32dec(b) != HEADER_MAGIC) return (0); bid += 32; /* * Verify header size */ if (archive_be16dec(b+4) != HEADER_SIZE) return (0); bid += 16; /* * Verify header version */ if (archive_be16dec(b+6) != HEADER_VERSION) return (0); bid += 16; /* * Verify type of checksum */ switch (archive_be32dec(b+24)) { case CKSUM_NONE: case CKSUM_SHA1: case CKSUM_MD5: bid += 32; break; default: return (0); } return (bid); } static int read_toc(struct archive_read *a) { struct xar *xar; struct xar_file *file; const unsigned char *b; uint64_t toc_compressed_size; uint64_t toc_uncompressed_size; uint32_t toc_chksum_alg; ssize_t bytes; int r; xar = (struct xar *)(a->format->data); /* * Read xar header. */ b = __archive_read_ahead(a, HEADER_SIZE, &bytes); if (bytes < 0) return ((int)bytes); if (bytes < HEADER_SIZE) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated archive header"); return (ARCHIVE_FATAL); } if (archive_be32dec(b) != HEADER_MAGIC) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header magic"); return (ARCHIVE_FATAL); } if (archive_be16dec(b+6) != HEADER_VERSION) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported header version(%d)", archive_be16dec(b+6)); return (ARCHIVE_FATAL); } toc_compressed_size = archive_be64dec(b+8); xar->toc_remaining = toc_compressed_size; toc_uncompressed_size = archive_be64dec(b+16); toc_chksum_alg = archive_be32dec(b+24); __archive_read_consume(a, HEADER_SIZE); xar->offset += HEADER_SIZE; xar->toc_total = 0; /* * Read TOC(Table of Contents). */ /* Initialize reading contents. */ r = move_reading_point(a, HEADER_SIZE); if (r != ARCHIVE_OK) return (r); r = rd_contents_init(a, GZIP, toc_chksum_alg, CKSUM_NONE); if (r != ARCHIVE_OK) return (r); #ifdef HAVE_LIBXML_XMLREADER_H r = xml2_read_toc(a); #elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) r = expat_read_toc(a); #endif if (r != ARCHIVE_OK) return (r); /* Set 'The HEAP' base. */ xar->h_base = xar->offset; if (xar->toc_total != toc_uncompressed_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "TOC uncompressed size error"); return (ARCHIVE_FATAL); } /* * Checksum TOC */ if (toc_chksum_alg != CKSUM_NONE) { r = move_reading_point(a, xar->toc_chksum_offset); if (r != ARCHIVE_OK) return (r); b = __archive_read_ahead(a, (size_t)xar->toc_chksum_size, &bytes); if (bytes < 0) return ((int)bytes); if ((uint64_t)bytes < xar->toc_chksum_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated archive file"); return (ARCHIVE_FATAL); } r = checksum_final(a, b, (size_t)xar->toc_chksum_size, NULL, 0); __archive_read_consume(a, xar->toc_chksum_size); xar->offset += xar->toc_chksum_size; if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* * Connect hardlinked files. */ for (file = xar->hdlink_orgs; file != NULL; file = file->hdnext) { struct hdlink **hdlink; for (hdlink = &(xar->hdlink_list); *hdlink != NULL; hdlink = &((*hdlink)->next)) { if ((*hdlink)->id == file->id) { struct hdlink *hltmp; struct xar_file *f2; int nlink = (*hdlink)->cnt + 1; file->nlink = nlink; for (f2 = (*hdlink)->files; f2 != NULL; f2 = f2->hdnext) { f2->nlink = nlink; archive_string_copy( &(f2->hardlink), &(file->pathname)); } /* Remove resolved files from hdlist_list. */ hltmp = *hdlink; *hdlink = hltmp->next; free(hltmp); break; } } } a->archive.archive_format = ARCHIVE_FORMAT_XAR; a->archive.archive_format_name = "xar"; return (ARCHIVE_OK); } static int xar_read_header(struct archive_read *a, struct archive_entry *entry) { struct xar *xar; struct xar_file *file; struct xattr *xattr; int r; xar = (struct xar *)(a->format->data); r = ARCHIVE_OK; if (xar->offset == 0) { /* Create a character conversion object. */ if (xar->sconv == NULL) { xar->sconv = archive_string_conversion_from_charset( &(a->archive), "UTF-8", 1); if (xar->sconv == NULL) return (ARCHIVE_FATAL); } /* Read TOC. */ r = read_toc(a); if (r != ARCHIVE_OK) return (r); } for (;;) { file = xar->file = heap_get_entry(&(xar->file_queue)); if (file == NULL) { xar->end_of_file = 1; return (ARCHIVE_EOF); } if ((file->mode & AE_IFMT) != AE_IFDIR) break; if (file->has != (HAS_PATHNAME | HAS_TYPE)) break; /* * If a file type is a directory and it does not have * any metadata, do not export. */ file_free(file); } archive_entry_set_atime(entry, file->atime, 0); archive_entry_set_ctime(entry, file->ctime, 0); archive_entry_set_mtime(entry, file->mtime, 0); archive_entry_set_gid(entry, file->gid); if (file->gname.length > 0 && archive_entry_copy_gname_l(entry, file->gname.s, archive_strlen(&(file->gname)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Gname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Gname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } archive_entry_set_uid(entry, file->uid); if (file->uname.length > 0 && archive_entry_copy_uname_l(entry, file->uname.s, archive_strlen(&(file->uname)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Uname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Uname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } archive_entry_set_mode(entry, file->mode); if (archive_entry_copy_pathname_l(entry, file->pathname.s, archive_strlen(&(file->pathname)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } if (file->symlink.length > 0 && archive_entry_copy_symlink_l(entry, file->symlink.s, archive_strlen(&(file->symlink)), xar->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Linkname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(xar->sconv)); r = ARCHIVE_WARN; } /* Set proper nlink. */ if ((file->mode & AE_IFMT) == AE_IFDIR) archive_entry_set_nlink(entry, file->subdirs + 2); else archive_entry_set_nlink(entry, file->nlink); archive_entry_set_size(entry, file->size); if (archive_strlen(&(file->hardlink)) > 0) archive_entry_set_hardlink(entry, file->hardlink.s); archive_entry_set_ino64(entry, file->ino64); if (file->has & HAS_DEV) archive_entry_set_dev(entry, file->dev); if (file->has & HAS_DEVMAJOR) archive_entry_set_devmajor(entry, file->devmajor); if (file->has & HAS_DEVMINOR) archive_entry_set_devminor(entry, file->devminor); if (archive_strlen(&(file->fflags_text)) > 0) archive_entry_copy_fflags_text(entry, file->fflags_text.s); xar->entry_init = 1; xar->entry_total = 0; xar->entry_remaining = file->length; xar->entry_size = file->size; xar->entry_encoding = file->encoding; xar->entry_a_sum = file->a_sum; xar->entry_e_sum = file->e_sum; /* * Read extended attributes. */ xattr = file->xattr_list; while (xattr != NULL) { const void *d; size_t outbytes, used; r = move_reading_point(a, xattr->offset); if (r != ARCHIVE_OK) break; r = rd_contents_init(a, xattr->encoding, xattr->a_sum.alg, xattr->e_sum.alg); if (r != ARCHIVE_OK) break; d = NULL; r = rd_contents(a, &d, &outbytes, &used, xattr->length); if (r != ARCHIVE_OK) break; if (outbytes != xattr->size) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompressed size error"); r = ARCHIVE_FATAL; break; } r = checksum_final(a, xattr->a_sum.val, xattr->a_sum.len, xattr->e_sum.val, xattr->e_sum.len); if (r != ARCHIVE_OK) break; archive_entry_xattr_add_entry(entry, xattr->name.s, d, outbytes); xattr = xattr->next; } if (r != ARCHIVE_OK) { file_free(file); return (r); } if (xar->entry_remaining > 0) /* Move reading point to the beginning of current * file contents. */ r = move_reading_point(a, file->offset); else r = ARCHIVE_OK; file_free(file); return (r); } static int xar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct xar *xar; size_t used; int r; xar = (struct xar *)(a->format->data); if (xar->entry_unconsumed) { __archive_read_consume(a, xar->entry_unconsumed); xar->entry_unconsumed = 0; } if (xar->end_of_file || xar->entry_remaining <= 0) { r = ARCHIVE_EOF; goto abort_read_data; } if (xar->entry_init) { r = rd_contents_init(a, xar->entry_encoding, xar->entry_a_sum.alg, xar->entry_e_sum.alg); if (r != ARCHIVE_OK) { xar->entry_remaining = 0; return (r); } xar->entry_init = 0; } *buff = NULL; r = rd_contents(a, buff, size, &used, xar->entry_remaining); if (r != ARCHIVE_OK) goto abort_read_data; *offset = xar->entry_total; xar->entry_total += *size; xar->total += *size; xar->offset += used; xar->entry_remaining -= used; xar->entry_unconsumed = used; if (xar->entry_remaining == 0) { if (xar->entry_total != xar->entry_size) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Decompressed size error"); r = ARCHIVE_FATAL; goto abort_read_data; } r = checksum_final(a, xar->entry_a_sum.val, xar->entry_a_sum.len, xar->entry_e_sum.val, xar->entry_e_sum.len); if (r != ARCHIVE_OK) goto abort_read_data; } return (ARCHIVE_OK); abort_read_data: *buff = NULL; *size = 0; *offset = xar->total; return (r); } static int xar_read_data_skip(struct archive_read *a) { struct xar *xar; int64_t bytes_skipped; xar = (struct xar *)(a->format->data); if (xar->end_of_file) return (ARCHIVE_EOF); bytes_skipped = __archive_read_consume(a, xar->entry_remaining + xar->entry_unconsumed); if (bytes_skipped < 0) return (ARCHIVE_FATAL); xar->offset += bytes_skipped; xar->entry_unconsumed = 0; return (ARCHIVE_OK); } static int xar_cleanup(struct archive_read *a) { struct xar *xar; struct hdlink *hdlink; int i; int r; xar = (struct xar *)(a->format->data); checksum_cleanup(a); r = decompression_cleanup(a); hdlink = xar->hdlink_list; while (hdlink != NULL) { struct hdlink *next = hdlink->next; free(hdlink); hdlink = next; } for (i = 0; i < xar->file_queue.used; i++) file_free(xar->file_queue.files[i]); free(xar->file_queue.files); while (xar->unknowntags != NULL) { struct unknown_tag *tag; tag = xar->unknowntags; xar->unknowntags = tag->next; archive_string_free(&(tag->name)); free(tag); } free(xar->outbuff); free(xar); a->format->data = NULL; return (r); } static int move_reading_point(struct archive_read *a, uint64_t offset) { struct xar *xar; xar = (struct xar *)(a->format->data); if (xar->offset - xar->h_base != offset) { /* Seek forward to the start of file contents. */ int64_t step; step = offset - (xar->offset - xar->h_base); if (step > 0) { step = __archive_read_consume(a, step); if (step < 0) return ((int)step); xar->offset += step; } else { int64_t pos = __archive_read_seek(a, offset, SEEK_SET); if (pos == ARCHIVE_FAILED) { archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Cannot seek."); return (ARCHIVE_FAILED); } xar->offset = pos; } } return (ARCHIVE_OK); } static int rd_contents_init(struct archive_read *a, enum enctype encoding, int a_sum_alg, int e_sum_alg) { int r; /* Init decompress library. */ if ((r = decompression_init(a, encoding)) != ARCHIVE_OK) return (r); /* Init checksum library. */ checksum_init(a, a_sum_alg, e_sum_alg); return (ARCHIVE_OK); } static int rd_contents(struct archive_read *a, const void **buff, size_t *size, size_t *used, uint64_t remaining) { const unsigned char *b; ssize_t bytes; /* Get whatever bytes are immediately available. */ b = __archive_read_ahead(a, 1, &bytes); if (bytes < 0) return ((int)bytes); if (bytes == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Truncated archive file"); return (ARCHIVE_FATAL); } if ((uint64_t)bytes > remaining) bytes = (ssize_t)remaining; /* * Decompress contents of file. */ *used = bytes; if (decompress(a, buff, size, b, used) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* * Update checksum of a compressed data and a extracted data. */ checksum_update(a, b, *used, *buff, *size); return (ARCHIVE_OK); } /* * Note that this implementation does not (and should not!) obey * locale settings; you cannot simply substitute strtol here, since * it does obey locale. */ static uint64_t atol10(const char *p, size_t char_cnt) { uint64_t l; int digit; l = 0; digit = *p - '0'; while (digit >= 0 && digit < 10 && char_cnt-- > 0) { l = (l * 10) + digit; digit = *++p - '0'; } return (l); } static int64_t atol8(const char *p, size_t char_cnt) { int64_t l; int digit; l = 0; while (char_cnt-- > 0) { if (*p >= '0' && *p <= '7') digit = *p - '0'; else break; p++; l <<= 3; l |= digit; } return (l); } static size_t atohex(unsigned char *b, size_t bsize, const char *p, size_t psize) { size_t fbsize = bsize; while (bsize && psize > 1) { unsigned char x; if (p[0] >= 'a' && p[0] <= 'z') x = (p[0] - 'a' + 0x0a) << 4; else if (p[0] >= 'A' && p[0] <= 'Z') x = (p[0] - 'A' + 0x0a) << 4; else if (p[0] >= '0' && p[0] <= '9') x = (p[0] - '0') << 4; else return (-1); if (p[1] >= 'a' && p[1] <= 'z') x |= p[1] - 'a' + 0x0a; else if (p[1] >= 'A' && p[1] <= 'Z') x |= p[1] - 'A' + 0x0a; else if (p[1] >= '0' && p[1] <= '9') x |= p[1] - '0'; else return (-1); *b++ = x; bsize--; p += 2; psize -= 2; } return (fbsize - bsize); } static time_t time_from_tm(struct tm *t) { #if HAVE_TIMEGM /* Use platform timegm() if available. */ return (timegm(t)); #elif HAVE__MKGMTIME64 return (_mkgmtime64(t)); #else /* Else use direct calculation using POSIX assumptions. */ /* First, fix up tm_yday based on the year/month/day. */ mktime(t); /* Then we can compute timegm() from first principles. */ return (t->tm_sec + t->tm_min * 60 + t->tm_hour * 3600 + t->tm_yday * 86400 + (t->tm_year - 70) * 31536000 + ((t->tm_year - 69) / 4) * 86400 - ((t->tm_year - 1) / 100) * 86400 + ((t->tm_year + 299) / 400) * 86400); #endif } static time_t parse_time(const char *p, size_t n) { struct tm tm; time_t t = 0; int64_t data; memset(&tm, 0, sizeof(tm)); if (n != 20) return (t); data = atol10(p, 4); if (data < 1900) return (t); tm.tm_year = (int)data - 1900; p += 4; if (*p++ != '-') return (t); data = atol10(p, 2); if (data < 1 || data > 12) return (t); tm.tm_mon = (int)data -1; p += 2; if (*p++ != '-') return (t); data = atol10(p, 2); if (data < 1 || data > 31) return (t); tm.tm_mday = (int)data; p += 2; if (*p++ != 'T') return (t); data = atol10(p, 2); if (data < 0 || data > 23) return (t); tm.tm_hour = (int)data; p += 2; if (*p++ != ':') return (t); data = atol10(p, 2); if (data < 0 || data > 59) return (t); tm.tm_min = (int)data; p += 2; if (*p++ != ':') return (t); data = atol10(p, 2); if (data < 0 || data > 60) return (t); tm.tm_sec = (int)data; #if 0 p += 2; if (*p != 'Z') return (t); #endif t = time_from_tm(&tm); return (t); } static int heap_add_entry(struct archive_read *a, struct heap_queue *heap, struct xar_file *file) { uint64_t file_id, parent_id; int hole, parent; /* Expand our pending files list as necessary. */ if (heap->used >= heap->allocated) { struct xar_file **new_pending_files; int new_size = heap->allocated * 2; if (heap->allocated < 1024) new_size = 1024; /* Overflow might keep us from growing the list. */ if (new_size <= heap->allocated) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } new_pending_files = (struct xar_file **) malloc(new_size * sizeof(new_pending_files[0])); if (new_pending_files == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } memcpy(new_pending_files, heap->files, heap->allocated * sizeof(new_pending_files[0])); if (heap->files != NULL) free(heap->files); heap->files = new_pending_files; heap->allocated = new_size; } file_id = file->id; /* * Start with hole at end, walk it up tree to find insertion point. */ hole = heap->used++; while (hole > 0) { parent = (hole - 1)/2; parent_id = heap->files[parent]->id; if (file_id >= parent_id) { heap->files[hole] = file; return (ARCHIVE_OK); } /* Move parent into hole <==> move hole up tree. */ heap->files[hole] = heap->files[parent]; hole = parent; } heap->files[0] = file; return (ARCHIVE_OK); } static struct xar_file * heap_get_entry(struct heap_queue *heap) { uint64_t a_id, b_id, c_id; int a, b, c; struct xar_file *r, *tmp; if (heap->used < 1) return (NULL); /* * The first file in the list is the earliest; we'll return this. */ r = heap->files[0]; /* * Move the last item in the heap to the root of the tree */ heap->files[0] = heap->files[--(heap->used)]; /* * Rebalance the heap. */ a = 0; /* Starting element and its heap key */ a_id = heap->files[a]->id; for (;;) { b = a + a + 1; /* First child */ if (b >= heap->used) return (r); b_id = heap->files[b]->id; c = b + 1; /* Use second child if it is smaller. */ if (c < heap->used) { c_id = heap->files[c]->id; if (c_id < b_id) { b = c; b_id = c_id; } } if (a_id <= b_id) return (r); tmp = heap->files[a]; heap->files[a] = heap->files[b]; heap->files[b] = tmp; a = b; } } static int add_link(struct archive_read *a, struct xar *xar, struct xar_file *file) { struct hdlink *hdlink; for (hdlink = xar->hdlink_list; hdlink != NULL; hdlink = hdlink->next) { if (hdlink->id == file->link) { file->hdnext = hdlink->files; hdlink->cnt++; hdlink->files = file; return (ARCHIVE_OK); } } hdlink = malloc(sizeof(*hdlink)); if (hdlink == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } file->hdnext = NULL; hdlink->id = file->link; hdlink->cnt = 1; hdlink->files = file; hdlink->next = xar->hdlink_list; xar->hdlink_list = hdlink; return (ARCHIVE_OK); } static void _checksum_init(struct chksumwork *sumwrk, int sum_alg) { sumwrk->alg = sum_alg; switch (sum_alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_init(&(sumwrk->sha1ctx)); break; case CKSUM_MD5: archive_md5_init(&(sumwrk->md5ctx)); break; } } static void _checksum_update(struct chksumwork *sumwrk, const void *buff, size_t size) { switch (sumwrk->alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_update(&(sumwrk->sha1ctx), buff, size); break; case CKSUM_MD5: archive_md5_update(&(sumwrk->md5ctx), buff, size); break; } } static int _checksum_final(struct chksumwork *sumwrk, const void *val, size_t len) { unsigned char sum[MAX_SUM_SIZE]; int r = ARCHIVE_OK; switch (sumwrk->alg) { case CKSUM_NONE: break; case CKSUM_SHA1: archive_sha1_final(&(sumwrk->sha1ctx), sum); if (len != SHA1_SIZE || memcmp(val, sum, SHA1_SIZE) != 0) r = ARCHIVE_FAILED; break; case CKSUM_MD5: archive_md5_final(&(sumwrk->md5ctx), sum); if (len != MD5_SIZE || memcmp(val, sum, MD5_SIZE) != 0) r = ARCHIVE_FAILED; break; } return (r); } static void checksum_init(struct archive_read *a, int a_sum_alg, int e_sum_alg) { struct xar *xar; xar = (struct xar *)(a->format->data); _checksum_init(&(xar->a_sumwrk), a_sum_alg); _checksum_init(&(xar->e_sumwrk), e_sum_alg); } static void checksum_update(struct archive_read *a, const void *abuff, size_t asize, const void *ebuff, size_t esize) { struct xar *xar; xar = (struct xar *)(a->format->data); _checksum_update(&(xar->a_sumwrk), abuff, asize); _checksum_update(&(xar->e_sumwrk), ebuff, esize); } static int checksum_final(struct archive_read *a, const void *a_sum_val, size_t a_sum_len, const void *e_sum_val, size_t e_sum_len) { struct xar *xar; int r; xar = (struct xar *)(a->format->data); r = _checksum_final(&(xar->a_sumwrk), a_sum_val, a_sum_len); if (r == ARCHIVE_OK) r = _checksum_final(&(xar->e_sumwrk), e_sum_val, e_sum_len); if (r != ARCHIVE_OK) archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Sumcheck error"); return (r); } static int decompression_init(struct archive_read *a, enum enctype encoding) { struct xar *xar; const char *detail; int r; xar = (struct xar *)(a->format->data); xar->rd_encoding = encoding; switch (encoding) { case NONE: break; case GZIP: if (xar->stream_valid) r = inflateReset(&(xar->stream)); else r = inflateInit(&(xar->stream)); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Couldn't initialize zlib stream."); return (ARCHIVE_FATAL); } xar->stream_valid = 1; xar->stream.total_in = 0; xar->stream.total_out = 0; break; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case BZIP2: if (xar->bzstream_valid) { BZ2_bzDecompressEnd(&(xar->bzstream)); xar->bzstream_valid = 0; } r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 0); if (r == BZ_MEM_ERROR) r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 1); if (r != BZ_OK) { int err = ARCHIVE_ERRNO_MISC; detail = NULL; switch (r) { case BZ_PARAM_ERROR: detail = "invalid setup parameter"; break; case BZ_MEM_ERROR: err = ENOMEM; detail = "out of memory"; break; case BZ_CONFIG_ERROR: detail = "mis-compiled library"; break; } archive_set_error(&a->archive, err, "Internal error initializing decompressor: %s", detail == NULL ? "??" : detail); xar->bzstream_valid = 0; return (ARCHIVE_FATAL); } xar->bzstream_valid = 1; xar->bzstream.total_in_lo32 = 0; xar->bzstream.total_in_hi32 = 0; xar->bzstream.total_out_lo32 = 0; xar->bzstream.total_out_hi32 = 0; break; #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) #if LZMA_VERSION_MAJOR >= 5 /* Effectively disable the limiter. */ #define LZMA_MEMLIMIT UINT64_MAX #else /* NOTE: This needs to check memory size which running system has. */ #define LZMA_MEMLIMIT (1U << 30) #endif case XZ: case LZMA: if (xar->lzstream_valid) { lzma_end(&(xar->lzstream)); xar->lzstream_valid = 0; } if (xar->entry_encoding == XZ) r = lzma_stream_decoder(&(xar->lzstream), LZMA_MEMLIMIT,/* memlimit */ LZMA_CONCATENATED); else r = lzma_alone_decoder(&(xar->lzstream), LZMA_MEMLIMIT);/* memlimit */ if (r != LZMA_OK) { switch (r) { case LZMA_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Internal error initializing " "compression library: " "Cannot allocate memory"); break; case LZMA_OPTIONS_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "compression library: " "Invalid or unsupported options"); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "lzma library"); break; } return (ARCHIVE_FATAL); } xar->lzstream_valid = 1; xar->lzstream.total_in = 0; xar->lzstream.total_out = 0; break; #endif /* * Unsupported compression. */ default: #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) case BZIP2: #endif #if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) case LZMA: case XZ: #endif switch (xar->entry_encoding) { case BZIP2: detail = "bzip2"; break; case LZMA: detail = "lzma"; break; case XZ: detail = "xz"; break; default: detail = "??"; break; } archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "%s compression not supported on this platform", detail); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } static int decompress(struct archive_read *a, const void **buff, size_t *outbytes, const void *b, size_t *used) { struct xar *xar; void *outbuff; size_t avail_in, avail_out; int r; xar = (struct xar *)(a->format->data); avail_in = *used; outbuff = (void *)(uintptr_t)*buff; if (outbuff == NULL) { if (xar->outbuff == NULL) { xar->outbuff = malloc(OUTBUFF_SIZE); if (xar->outbuff == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory for out buffer"); return (ARCHIVE_FATAL); } } outbuff = xar->outbuff; *buff = outbuff; avail_out = OUTBUFF_SIZE; } else avail_out = *outbytes; switch (xar->rd_encoding) { case GZIP: xar->stream.next_in = (Bytef *)(uintptr_t)b; xar->stream.avail_in = avail_in; xar->stream.next_out = (unsigned char *)outbuff; xar->stream.avail_out = avail_out; r = inflate(&(xar->stream), 0); switch (r) { case Z_OK: /* Decompressor made some progress.*/ case Z_STREAM_END: /* Found end of stream. */ break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "File decompression failed (%d)", r); return (ARCHIVE_FATAL); } *used = avail_in - xar->stream.avail_in; *outbytes = avail_out - xar->stream.avail_out; break; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case BZIP2: xar->bzstream.next_in = (char *)(uintptr_t)b; xar->bzstream.avail_in = avail_in; xar->bzstream.next_out = (char *)outbuff; xar->bzstream.avail_out = avail_out; r = BZ2_bzDecompress(&(xar->bzstream)); switch (r) { case BZ_STREAM_END: /* Found end of stream. */ switch (BZ2_bzDecompressEnd(&(xar->bzstream))) { case BZ_OK: break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Failed to clean up decompressor"); return (ARCHIVE_FATAL); } xar->bzstream_valid = 0; /* FALLTHROUGH */ case BZ_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "bzip decompression failed"); return (ARCHIVE_FATAL); } *used = avail_in - xar->bzstream.avail_in; *outbytes = avail_out - xar->bzstream.avail_out; break; #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) case LZMA: case XZ: xar->lzstream.next_in = b; xar->lzstream.avail_in = avail_in; xar->lzstream.next_out = (unsigned char *)outbuff; xar->lzstream.avail_out = avail_out; r = lzma_code(&(xar->lzstream), LZMA_RUN); switch (r) { case LZMA_STREAM_END: /* Found end of stream. */ lzma_end(&(xar->lzstream)); xar->lzstream_valid = 0; /* FALLTHROUGH */ case LZMA_OK: /* Decompressor made some progress. */ break; default: archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "%s decompression failed(%d)", (xar->entry_encoding == XZ)?"xz":"lzma", r); return (ARCHIVE_FATAL); } *used = avail_in - xar->lzstream.avail_in; *outbytes = avail_out - xar->lzstream.avail_out; break; #endif #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) case BZIP2: #endif #if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) case LZMA: case XZ: #endif case NONE: default: if (outbuff == xar->outbuff) { *buff = b; *used = avail_in; *outbytes = avail_in; } else { if (avail_out > avail_in) avail_out = avail_in; memcpy(outbuff, b, avail_out); *used = avail_out; *outbytes = avail_out; } break; } return (ARCHIVE_OK); } static int decompression_cleanup(struct archive_read *a) { struct xar *xar; int r; xar = (struct xar *)(a->format->data); r = ARCHIVE_OK; if (xar->stream_valid) { if (inflateEnd(&(xar->stream)) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up zlib decompressor"); r = ARCHIVE_FATAL; } } #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) if (xar->bzstream_valid) { if (BZ2_bzDecompressEnd(&(xar->bzstream)) != BZ_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up bzip2 decompressor"); r = ARCHIVE_FATAL; } } #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) if (xar->lzstream_valid) lzma_end(&(xar->lzstream)); #elif defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) if (xar->lzstream_valid) { if (lzmadec_end(&(xar->lzstream)) != LZMADEC_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up lzmadec decompressor"); r = ARCHIVE_FATAL; } } #endif return (r); } static void checksum_cleanup(struct archive_read *a) { struct xar *xar; xar = (struct xar *)(a->format->data); _checksum_final(&(xar->a_sumwrk), NULL, 0); _checksum_final(&(xar->e_sumwrk), NULL, 0); } static void xmlattr_cleanup(struct xmlattr_list *list) { struct xmlattr *attr, *next; attr = list->first; while (attr != NULL) { next = attr->next; free(attr->name); free(attr->value); free(attr); attr = next; } list->first = NULL; list->last = &(list->first); } static int file_new(struct archive_read *a, struct xar *xar, struct xmlattr_list *list) { struct xar_file *file; struct xmlattr *attr; file = calloc(1, sizeof(*file)); if (file == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } file->parent = xar->file; file->mode = 0777 | AE_IFREG; file->atime = time(NULL); file->mtime = time(NULL); xar->file = file; xar->xattr = NULL; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "id") == 0) file->id = atol10(attr->value, strlen(attr->value)); } file->nlink = 1; if (heap_add_entry(a, &(xar->file_queue), file) != ARCHIVE_OK) return (ARCHIVE_FATAL); return (ARCHIVE_OK); } static void file_free(struct xar_file *file) { struct xattr *xattr; archive_string_free(&(file->pathname)); archive_string_free(&(file->symlink)); archive_string_free(&(file->uname)); archive_string_free(&(file->gname)); archive_string_free(&(file->hardlink)); xattr = file->xattr_list; while (xattr != NULL) { struct xattr *next; next = xattr->next; xattr_free(xattr); xattr = next; } free(file); } static int xattr_new(struct archive_read *a, struct xar *xar, struct xmlattr_list *list) { struct xattr *xattr, **nx; struct xmlattr *attr; xattr = calloc(1, sizeof(*xattr)); if (xattr == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } xar->xattr = xattr; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "id") == 0) xattr->id = atol10(attr->value, strlen(attr->value)); } /* Chain to xattr list. */ for (nx = &(xar->file->xattr_list); *nx != NULL; nx = &((*nx)->next)) { if (xattr->id < (*nx)->id) break; } xattr->next = *nx; *nx = xattr; return (ARCHIVE_OK); } static void xattr_free(struct xattr *xattr) { archive_string_free(&(xattr->name)); free(xattr); } static int getencoding(struct xmlattr_list *list) { struct xmlattr *attr; enum enctype encoding = NONE; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "style") == 0) { if (strcmp(attr->value, "application/octet-stream") == 0) encoding = NONE; else if (strcmp(attr->value, "application/x-gzip") == 0) encoding = GZIP; else if (strcmp(attr->value, "application/x-bzip2") == 0) encoding = BZIP2; else if (strcmp(attr->value, "application/x-lzma") == 0) encoding = LZMA; else if (strcmp(attr->value, "application/x-xz") == 0) encoding = XZ; } } return (encoding); } static int getsumalgorithm(struct xmlattr_list *list) { struct xmlattr *attr; int alg = CKSUM_NONE; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "style") == 0) { const char *v = attr->value; if ((v[0] == 'S' || v[0] == 's') && (v[1] == 'H' || v[1] == 'h') && (v[2] == 'A' || v[2] == 'a') && v[3] == '1' && v[4] == '\0') alg = CKSUM_SHA1; if ((v[0] == 'M' || v[0] == 'm') && (v[1] == 'D' || v[1] == 'd') && v[2] == '5' && v[3] == '\0') alg = CKSUM_MD5; } } return (alg); } static int unknowntag_start(struct archive_read *a, struct xar *xar, const char *name) { struct unknown_tag *tag; tag = malloc(sizeof(*tag)); if (tag == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } tag->next = xar->unknowntags; archive_string_init(&(tag->name)); archive_strcpy(&(tag->name), name); if (xar->unknowntags == NULL) { #if DEBUG fprintf(stderr, "UNKNOWNTAG_START:%s\n", name); #endif xar->xmlsts_unknown = xar->xmlsts; xar->xmlsts = UNKNOWN; } xar->unknowntags = tag; return (ARCHIVE_OK); } static void unknowntag_end(struct xar *xar, const char *name) { struct unknown_tag *tag; tag = xar->unknowntags; if (tag == NULL || name == NULL) return; if (strcmp(tag->name.s, name) == 0) { xar->unknowntags = tag->next; archive_string_free(&(tag->name)); free(tag); if (xar->unknowntags == NULL) { #if DEBUG fprintf(stderr, "UNKNOWNTAG_END:%s\n", name); #endif xar->xmlsts = xar->xmlsts_unknown; } } } static int xml_start(struct archive_read *a, const char *name, struct xmlattr_list *list) { struct xar *xar; struct xmlattr *attr; xar = (struct xar *)(a->format->data); #if DEBUG fprintf(stderr, "xml_sta:[%s]\n", name); for (attr = list->first; attr != NULL; attr = attr->next) fprintf(stderr, " attr:\"%s\"=\"%s\"\n", attr->name, attr->value); #endif xar->base64text = 0; switch (xar->xmlsts) { case INIT: if (strcmp(name, "xar") == 0) xar->xmlsts = XAR; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case XAR: if (strcmp(name, "toc") == 0) xar->xmlsts = TOC; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC: if (strcmp(name, "creation-time") == 0) xar->xmlsts = TOC_CREATION_TIME; else if (strcmp(name, "checksum") == 0) xar->xmlsts = TOC_CHECKSUM; else if (strcmp(name, "file") == 0) { if (file_new(a, xar, list) != ARCHIVE_OK) return (ARCHIVE_FATAL); xar->xmlsts = TOC_FILE; } else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC_CHECKSUM: if (strcmp(name, "offset") == 0) xar->xmlsts = TOC_CHECKSUM_OFFSET; else if (strcmp(name, "size") == 0) xar->xmlsts = TOC_CHECKSUM_SIZE; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC_FILE: if (strcmp(name, "file") == 0) { if (file_new(a, xar, list) != ARCHIVE_OK) return (ARCHIVE_FATAL); } else if (strcmp(name, "data") == 0) xar->xmlsts = FILE_DATA; else if (strcmp(name, "ea") == 0) { if (xattr_new(a, xar, list) != ARCHIVE_OK) return (ARCHIVE_FATAL); xar->xmlsts = FILE_EA; } else if (strcmp(name, "ctime") == 0) xar->xmlsts = FILE_CTIME; else if (strcmp(name, "mtime") == 0) xar->xmlsts = FILE_MTIME; else if (strcmp(name, "atime") == 0) xar->xmlsts = FILE_ATIME; else if (strcmp(name, "group") == 0) xar->xmlsts = FILE_GROUP; else if (strcmp(name, "gid") == 0) xar->xmlsts = FILE_GID; else if (strcmp(name, "user") == 0) xar->xmlsts = FILE_USER; else if (strcmp(name, "uid") == 0) xar->xmlsts = FILE_UID; else if (strcmp(name, "mode") == 0) xar->xmlsts = FILE_MODE; else if (strcmp(name, "device") == 0) xar->xmlsts = FILE_DEVICE; else if (strcmp(name, "deviceno") == 0) xar->xmlsts = FILE_DEVICENO; else if (strcmp(name, "inode") == 0) xar->xmlsts = FILE_INODE; else if (strcmp(name, "link") == 0) xar->xmlsts = FILE_LINK; else if (strcmp(name, "type") == 0) { xar->xmlsts = FILE_TYPE; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "link") != 0) continue; if (strcmp(attr->value, "original") == 0) { xar->file->hdnext = xar->hdlink_orgs; xar->hdlink_orgs = xar->file; } else { xar->file->link = (unsigned)atol10(attr->value, strlen(attr->value)); if (xar->file->link > 0) if (add_link(a, xar, xar->file) != ARCHIVE_OK) { return (ARCHIVE_FATAL); }; } } } else if (strcmp(name, "name") == 0) { xar->xmlsts = FILE_NAME; for (attr = list->first; attr != NULL; attr = attr->next) { if (strcmp(attr->name, "enctype") == 0 && strcmp(attr->value, "base64") == 0) xar->base64text = 1; } } else if (strcmp(name, "acl") == 0) xar->xmlsts = FILE_ACL; else if (strcmp(name, "flags") == 0) xar->xmlsts = FILE_FLAGS; else if (strcmp(name, "ext2") == 0) xar->xmlsts = FILE_EXT2; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_DATA: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_DATA_LENGTH; else if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_DATA_OFFSET; else if (strcmp(name, "size") == 0) xar->xmlsts = FILE_DATA_SIZE; else if (strcmp(name, "encoding") == 0) { xar->xmlsts = FILE_DATA_ENCODING; xar->file->encoding = getencoding(list); } else if (strcmp(name, "archived-checksum") == 0) { xar->xmlsts = FILE_DATA_A_CHECKSUM; xar->file->a_sum.alg = getsumalgorithm(list); } else if (strcmp(name, "extracted-checksum") == 0) { xar->xmlsts = FILE_DATA_E_CHECKSUM; xar->file->e_sum.alg = getsumalgorithm(list); } else if (strcmp(name, "content") == 0) xar->xmlsts = FILE_DATA_CONTENT; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_DEVICE: if (strcmp(name, "major") == 0) xar->xmlsts = FILE_DEVICE_MAJOR; else if (strcmp(name, "minor") == 0) xar->xmlsts = FILE_DEVICE_MINOR; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_DATA_CONTENT: if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_EA: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_EA_LENGTH; else if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_EA_OFFSET; else if (strcmp(name, "size") == 0) xar->xmlsts = FILE_EA_SIZE; else if (strcmp(name, "encoding") == 0) { xar->xmlsts = FILE_EA_ENCODING; xar->xattr->encoding = getencoding(list); } else if (strcmp(name, "archived-checksum") == 0) xar->xmlsts = FILE_EA_A_CHECKSUM; else if (strcmp(name, "extracted-checksum") == 0) xar->xmlsts = FILE_EA_E_CHECKSUM; else if (strcmp(name, "name") == 0) xar->xmlsts = FILE_EA_NAME; else if (strcmp(name, "fstype") == 0) xar->xmlsts = FILE_EA_FSTYPE; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_ACL: if (strcmp(name, "appleextended") == 0) xar->xmlsts = FILE_ACL_APPLEEXTENDED; else if (strcmp(name, "default") == 0) xar->xmlsts = FILE_ACL_DEFAULT; else if (strcmp(name, "access") == 0) xar->xmlsts = FILE_ACL_ACCESS; else if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_FLAGS: if (!xml_parse_file_flags(xar, name)) if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case FILE_EXT2: if (!xml_parse_file_ext2(xar, name)) if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; case TOC_CREATION_TIME: case TOC_CHECKSUM_OFFSET: case TOC_CHECKSUM_SIZE: case FILE_DATA_LENGTH: case FILE_DATA_OFFSET: case FILE_DATA_SIZE: case FILE_DATA_ENCODING: case FILE_DATA_A_CHECKSUM: case FILE_DATA_E_CHECKSUM: case FILE_EA_LENGTH: case FILE_EA_OFFSET: case FILE_EA_SIZE: case FILE_EA_ENCODING: case FILE_EA_A_CHECKSUM: case FILE_EA_E_CHECKSUM: case FILE_EA_NAME: case FILE_EA_FSTYPE: case FILE_CTIME: case FILE_MTIME: case FILE_ATIME: case FILE_GROUP: case FILE_GID: case FILE_USER: case FILE_UID: case FILE_INODE: case FILE_DEVICE_MAJOR: case FILE_DEVICE_MINOR: case FILE_DEVICENO: case FILE_MODE: case FILE_TYPE: case FILE_LINK: case FILE_NAME: case FILE_ACL_DEFAULT: case FILE_ACL_ACCESS: case FILE_ACL_APPLEEXTENDED: case FILE_FLAGS_USER_NODUMP: case FILE_FLAGS_USER_IMMUTABLE: case FILE_FLAGS_USER_APPEND: case FILE_FLAGS_USER_OPAQUE: case FILE_FLAGS_USER_NOUNLINK: case FILE_FLAGS_SYS_ARCHIVED: case FILE_FLAGS_SYS_IMMUTABLE: case FILE_FLAGS_SYS_APPEND: case FILE_FLAGS_SYS_NOUNLINK: case FILE_FLAGS_SYS_SNAPSHOT: case FILE_EXT2_SecureDeletion: case FILE_EXT2_Undelete: case FILE_EXT2_Compress: case FILE_EXT2_Synchronous: case FILE_EXT2_Immutable: case FILE_EXT2_AppendOnly: case FILE_EXT2_NoDump: case FILE_EXT2_NoAtime: case FILE_EXT2_CompDirty: case FILE_EXT2_CompBlock: case FILE_EXT2_NoCompBlock: case FILE_EXT2_CompError: case FILE_EXT2_BTree: case FILE_EXT2_HashIndexed: case FILE_EXT2_iMagic: case FILE_EXT2_Journaled: case FILE_EXT2_NoTail: case FILE_EXT2_DirSync: case FILE_EXT2_TopDir: case FILE_EXT2_Reserved: case UNKNOWN: if (unknowntag_start(a, xar, name) != ARCHIVE_OK) return (ARCHIVE_FATAL); break; } return (ARCHIVE_OK); } static void xml_end(void *userData, const char *name) { struct archive_read *a; struct xar *xar; a = (struct archive_read *)userData; xar = (struct xar *)(a->format->data); #if DEBUG fprintf(stderr, "xml_end:[%s]\n", name); #endif switch (xar->xmlsts) { case INIT: break; case XAR: if (strcmp(name, "xar") == 0) xar->xmlsts = INIT; break; case TOC: if (strcmp(name, "toc") == 0) xar->xmlsts = XAR; break; case TOC_CREATION_TIME: if (strcmp(name, "creation-time") == 0) xar->xmlsts = TOC; break; case TOC_CHECKSUM: if (strcmp(name, "checksum") == 0) xar->xmlsts = TOC; break; case TOC_CHECKSUM_OFFSET: if (strcmp(name, "offset") == 0) xar->xmlsts = TOC_CHECKSUM; break; case TOC_CHECKSUM_SIZE: if (strcmp(name, "size") == 0) xar->xmlsts = TOC_CHECKSUM; break; case TOC_FILE: if (strcmp(name, "file") == 0) { if (xar->file->parent != NULL && ((xar->file->mode & AE_IFMT) == AE_IFDIR)) xar->file->parent->subdirs++; xar->file = xar->file->parent; if (xar->file == NULL) xar->xmlsts = TOC; } break; case FILE_DATA: if (strcmp(name, "data") == 0) xar->xmlsts = TOC_FILE; break; case FILE_DATA_LENGTH: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_OFFSET: if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_SIZE: if (strcmp(name, "size") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_ENCODING: if (strcmp(name, "encoding") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_A_CHECKSUM: if (strcmp(name, "archived-checksum") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_E_CHECKSUM: if (strcmp(name, "extracted-checksum") == 0) xar->xmlsts = FILE_DATA; break; case FILE_DATA_CONTENT: if (strcmp(name, "content") == 0) xar->xmlsts = FILE_DATA; break; case FILE_EA: if (strcmp(name, "ea") == 0) { xar->xmlsts = TOC_FILE; xar->xattr = NULL; } break; case FILE_EA_LENGTH: if (strcmp(name, "length") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_OFFSET: if (strcmp(name, "offset") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_SIZE: if (strcmp(name, "size") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_ENCODING: if (strcmp(name, "encoding") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_A_CHECKSUM: if (strcmp(name, "archived-checksum") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_E_CHECKSUM: if (strcmp(name, "extracted-checksum") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_NAME: if (strcmp(name, "name") == 0) xar->xmlsts = FILE_EA; break; case FILE_EA_FSTYPE: if (strcmp(name, "fstype") == 0) xar->xmlsts = FILE_EA; break; case FILE_CTIME: if (strcmp(name, "ctime") == 0) xar->xmlsts = TOC_FILE; break; case FILE_MTIME: if (strcmp(name, "mtime") == 0) xar->xmlsts = TOC_FILE; break; case FILE_ATIME: if (strcmp(name, "atime") == 0) xar->xmlsts = TOC_FILE; break; case FILE_GROUP: if (strcmp(name, "group") == 0) xar->xmlsts = TOC_FILE; break; case FILE_GID: if (strcmp(name, "gid") == 0) xar->xmlsts = TOC_FILE; break; case FILE_USER: if (strcmp(name, "user") == 0) xar->xmlsts = TOC_FILE; break; case FILE_UID: if (strcmp(name, "uid") == 0) xar->xmlsts = TOC_FILE; break; case FILE_MODE: if (strcmp(name, "mode") == 0) xar->xmlsts = TOC_FILE; break; case FILE_DEVICE: if (strcmp(name, "device") == 0) xar->xmlsts = TOC_FILE; break; case FILE_DEVICE_MAJOR: if (strcmp(name, "major") == 0) xar->xmlsts = FILE_DEVICE; break; case FILE_DEVICE_MINOR: if (strcmp(name, "minor") == 0) xar->xmlsts = FILE_DEVICE; break; case FILE_DEVICENO: if (strcmp(name, "deviceno") == 0) xar->xmlsts = TOC_FILE; break; case FILE_INODE: if (strcmp(name, "inode") == 0) xar->xmlsts = TOC_FILE; break; case FILE_LINK: if (strcmp(name, "link") == 0) xar->xmlsts = TOC_FILE; break; case FILE_TYPE: if (strcmp(name, "type") == 0) xar->xmlsts = TOC_FILE; break; case FILE_NAME: if (strcmp(name, "name") == 0) xar->xmlsts = TOC_FILE; break; case FILE_ACL: if (strcmp(name, "acl") == 0) xar->xmlsts = TOC_FILE; break; case FILE_ACL_DEFAULT: if (strcmp(name, "default") == 0) xar->xmlsts = FILE_ACL; break; case FILE_ACL_ACCESS: if (strcmp(name, "access") == 0) xar->xmlsts = FILE_ACL; break; case FILE_ACL_APPLEEXTENDED: if (strcmp(name, "appleextended") == 0) xar->xmlsts = FILE_ACL; break; case FILE_FLAGS: if (strcmp(name, "flags") == 0) xar->xmlsts = TOC_FILE; break; case FILE_FLAGS_USER_NODUMP: if (strcmp(name, "UserNoDump") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_IMMUTABLE: if (strcmp(name, "UserImmutable") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_APPEND: if (strcmp(name, "UserAppend") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_OPAQUE: if (strcmp(name, "UserOpaque") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_USER_NOUNLINK: if (strcmp(name, "UserNoUnlink") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_ARCHIVED: if (strcmp(name, "SystemArchived") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_IMMUTABLE: if (strcmp(name, "SystemImmutable") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_APPEND: if (strcmp(name, "SystemAppend") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_NOUNLINK: if (strcmp(name, "SystemNoUnlink") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_FLAGS_SYS_SNAPSHOT: if (strcmp(name, "SystemSnapshot") == 0) xar->xmlsts = FILE_FLAGS; break; case FILE_EXT2: if (strcmp(name, "ext2") == 0) xar->xmlsts = TOC_FILE; break; case FILE_EXT2_SecureDeletion: if (strcmp(name, "SecureDeletion") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Undelete: if (strcmp(name, "Undelete") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Compress: if (strcmp(name, "Compress") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Synchronous: if (strcmp(name, "Synchronous") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Immutable: if (strcmp(name, "Immutable") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_AppendOnly: if (strcmp(name, "AppendOnly") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoDump: if (strcmp(name, "NoDump") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoAtime: if (strcmp(name, "NoAtime") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_CompDirty: if (strcmp(name, "CompDirty") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_CompBlock: if (strcmp(name, "CompBlock") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoCompBlock: if (strcmp(name, "NoCompBlock") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_CompError: if (strcmp(name, "CompError") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_BTree: if (strcmp(name, "BTree") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_HashIndexed: if (strcmp(name, "HashIndexed") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_iMagic: if (strcmp(name, "iMagic") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Journaled: if (strcmp(name, "Journaled") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_NoTail: if (strcmp(name, "NoTail") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_DirSync: if (strcmp(name, "DirSync") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_TopDir: if (strcmp(name, "TopDir") == 0) xar->xmlsts = FILE_EXT2; break; case FILE_EXT2_Reserved: if (strcmp(name, "Reserved") == 0) xar->xmlsts = FILE_EXT2; break; case UNKNOWN: unknowntag_end(xar, name); break; } } static const int base64[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 */ }; static void strappend_base64(struct xar *xar, struct archive_string *as, const char *s, size_t l) { unsigned char buff[256]; unsigned char *out; const unsigned char *b; size_t len; (void)xar; /* UNUSED */ len = 0; out = buff; b = (const unsigned char *)s; while (l > 0) { int n = 0; if (l > 0) { if (base64[b[0]] < 0 || base64[b[1]] < 0) break; n = base64[*b++] << 18; n |= base64[*b++] << 12; *out++ = n >> 16; len++; l -= 2; } if (l > 0) { if (base64[*b] < 0) break; n |= base64[*b++] << 6; *out++ = (n >> 8) & 0xFF; len++; --l; } if (l > 0) { if (base64[*b] < 0) break; n |= base64[*b++]; *out++ = n & 0xFF; len++; --l; } if (len+3 >= sizeof(buff)) { archive_strncat(as, (const char *)buff, len); len = 0; out = buff; } } if (len > 0) archive_strncat(as, (const char *)buff, len); } static void xml_data(void *userData, const char *s, int len) { struct archive_read *a; struct xar *xar; a = (struct archive_read *)userData; xar = (struct xar *)(a->format->data); #if DEBUG { char buff[1024]; if (len > (int)(sizeof(buff)-1)) len = (int)(sizeof(buff)-1); strncpy(buff, s, len); buff[len] = 0; fprintf(stderr, "\tlen=%d:\"%s\"\n", len, buff); } #endif switch (xar->xmlsts) { case TOC_CHECKSUM_OFFSET: xar->toc_chksum_offset = atol10(s, len); break; case TOC_CHECKSUM_SIZE: xar->toc_chksum_size = atol10(s, len); break; default: break; } if (xar->file == NULL) return; switch (xar->xmlsts) { case FILE_NAME: if (xar->file->parent != NULL) { archive_string_concat(&(xar->file->pathname), &(xar->file->parent->pathname)); archive_strappend_char(&(xar->file->pathname), '/'); } xar->file->has |= HAS_PATHNAME; if (xar->base64text) { strappend_base64(xar, &(xar->file->pathname), s, len); } else archive_strncat(&(xar->file->pathname), s, len); break; case FILE_LINK: xar->file->has |= HAS_SYMLINK; archive_strncpy(&(xar->file->symlink), s, len); break; case FILE_TYPE: if (strncmp("file", s, len) == 0 || strncmp("hardlink", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFREG; if (strncmp("directory", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFDIR; if (strncmp("symlink", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFLNK; if (strncmp("character special", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFCHR; if (strncmp("block special", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFBLK; if (strncmp("socket", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFSOCK; if (strncmp("fifo", s, len) == 0) xar->file->mode = (xar->file->mode & ~AE_IFMT) | AE_IFIFO; xar->file->has |= HAS_TYPE; break; case FILE_INODE: xar->file->has |= HAS_INO; xar->file->ino64 = atol10(s, len); break; case FILE_DEVICE_MAJOR: xar->file->has |= HAS_DEVMAJOR; xar->file->devmajor = (dev_t)atol10(s, len); break; case FILE_DEVICE_MINOR: xar->file->has |= HAS_DEVMINOR; xar->file->devminor = (dev_t)atol10(s, len); break; case FILE_DEVICENO: xar->file->has |= HAS_DEV; xar->file->dev = (dev_t)atol10(s, len); break; case FILE_MODE: xar->file->has |= HAS_MODE; xar->file->mode = (xar->file->mode & AE_IFMT) | ((mode_t)(atol8(s, len)) & ~AE_IFMT); break; case FILE_GROUP: xar->file->has |= HAS_GID; archive_strncpy(&(xar->file->gname), s, len); break; case FILE_GID: xar->file->has |= HAS_GID; xar->file->gid = atol10(s, len); break; case FILE_USER: xar->file->has |= HAS_UID; archive_strncpy(&(xar->file->uname), s, len); break; case FILE_UID: xar->file->has |= HAS_UID; xar->file->uid = atol10(s, len); break; case FILE_CTIME: xar->file->has |= HAS_TIME; xar->file->ctime = parse_time(s, len); break; case FILE_MTIME: xar->file->has |= HAS_TIME; xar->file->mtime = parse_time(s, len); break; case FILE_ATIME: xar->file->has |= HAS_TIME; xar->file->atime = parse_time(s, len); break; case FILE_DATA_LENGTH: xar->file->has |= HAS_DATA; xar->file->length = atol10(s, len); break; case FILE_DATA_OFFSET: xar->file->has |= HAS_DATA; xar->file->offset = atol10(s, len); break; case FILE_DATA_SIZE: xar->file->has |= HAS_DATA; xar->file->size = atol10(s, len); break; case FILE_DATA_A_CHECKSUM: xar->file->a_sum.len = atohex(xar->file->a_sum.val, sizeof(xar->file->a_sum.val), s, len); break; case FILE_DATA_E_CHECKSUM: xar->file->e_sum.len = atohex(xar->file->e_sum.val, sizeof(xar->file->e_sum.val), s, len); break; case FILE_EA_LENGTH: xar->file->has |= HAS_XATTR; xar->xattr->length = atol10(s, len); break; case FILE_EA_OFFSET: xar->file->has |= HAS_XATTR; xar->xattr->offset = atol10(s, len); break; case FILE_EA_SIZE: xar->file->has |= HAS_XATTR; xar->xattr->size = atol10(s, len); break; case FILE_EA_A_CHECKSUM: xar->file->has |= HAS_XATTR; xar->xattr->a_sum.len = atohex(xar->xattr->a_sum.val, sizeof(xar->xattr->a_sum.val), s, len); break; case FILE_EA_E_CHECKSUM: xar->file->has |= HAS_XATTR; xar->xattr->e_sum.len = atohex(xar->xattr->e_sum.val, sizeof(xar->xattr->e_sum.val), s, len); break; case FILE_EA_NAME: xar->file->has |= HAS_XATTR; archive_strncpy(&(xar->xattr->name), s, len); break; case FILE_EA_FSTYPE: xar->file->has |= HAS_XATTR; archive_strncpy(&(xar->xattr->fstype), s, len); break; break; case FILE_ACL_DEFAULT: case FILE_ACL_ACCESS: case FILE_ACL_APPLEEXTENDED: xar->file->has |= HAS_ACL; /* TODO */ break; case INIT: case XAR: case TOC: case TOC_CREATION_TIME: case TOC_CHECKSUM: case TOC_CHECKSUM_OFFSET: case TOC_CHECKSUM_SIZE: case TOC_FILE: case FILE_DATA: case FILE_DATA_ENCODING: case FILE_DATA_CONTENT: case FILE_DEVICE: case FILE_EA: case FILE_EA_ENCODING: case FILE_ACL: case FILE_FLAGS: case FILE_FLAGS_USER_NODUMP: case FILE_FLAGS_USER_IMMUTABLE: case FILE_FLAGS_USER_APPEND: case FILE_FLAGS_USER_OPAQUE: case FILE_FLAGS_USER_NOUNLINK: case FILE_FLAGS_SYS_ARCHIVED: case FILE_FLAGS_SYS_IMMUTABLE: case FILE_FLAGS_SYS_APPEND: case FILE_FLAGS_SYS_NOUNLINK: case FILE_FLAGS_SYS_SNAPSHOT: case FILE_EXT2: case FILE_EXT2_SecureDeletion: case FILE_EXT2_Undelete: case FILE_EXT2_Compress: case FILE_EXT2_Synchronous: case FILE_EXT2_Immutable: case FILE_EXT2_AppendOnly: case FILE_EXT2_NoDump: case FILE_EXT2_NoAtime: case FILE_EXT2_CompDirty: case FILE_EXT2_CompBlock: case FILE_EXT2_NoCompBlock: case FILE_EXT2_CompError: case FILE_EXT2_BTree: case FILE_EXT2_HashIndexed: case FILE_EXT2_iMagic: case FILE_EXT2_Journaled: case FILE_EXT2_NoTail: case FILE_EXT2_DirSync: case FILE_EXT2_TopDir: case FILE_EXT2_Reserved: case UNKNOWN: break; } } /* * BSD file flags. */ static int xml_parse_file_flags(struct xar *xar, const char *name) { const char *flag = NULL; if (strcmp(name, "UserNoDump") == 0) { xar->xmlsts = FILE_FLAGS_USER_NODUMP; flag = "nodump"; } else if (strcmp(name, "UserImmutable") == 0) { xar->xmlsts = FILE_FLAGS_USER_IMMUTABLE; flag = "uimmutable"; } else if (strcmp(name, "UserAppend") == 0) { xar->xmlsts = FILE_FLAGS_USER_APPEND; flag = "uappend"; } else if (strcmp(name, "UserOpaque") == 0) { xar->xmlsts = FILE_FLAGS_USER_OPAQUE; flag = "opaque"; } else if (strcmp(name, "UserNoUnlink") == 0) { xar->xmlsts = FILE_FLAGS_USER_NOUNLINK; flag = "nouunlink"; } else if (strcmp(name, "SystemArchived") == 0) { xar->xmlsts = FILE_FLAGS_SYS_ARCHIVED; flag = "archived"; } else if (strcmp(name, "SystemImmutable") == 0) { xar->xmlsts = FILE_FLAGS_SYS_IMMUTABLE; flag = "simmutable"; } else if (strcmp(name, "SystemAppend") == 0) { xar->xmlsts = FILE_FLAGS_SYS_APPEND; flag = "sappend"; } else if (strcmp(name, "SystemNoUnlink") == 0) { xar->xmlsts = FILE_FLAGS_SYS_NOUNLINK; flag = "nosunlink"; } else if (strcmp(name, "SystemSnapshot") == 0) { xar->xmlsts = FILE_FLAGS_SYS_SNAPSHOT; flag = "snapshot"; } if (flag == NULL) return (0); xar->file->has |= HAS_FFLAGS; if (archive_strlen(&(xar->file->fflags_text)) > 0) archive_strappend_char(&(xar->file->fflags_text), ','); archive_strcat(&(xar->file->fflags_text), flag); return (1); } /* * Linux file flags. */ static int xml_parse_file_ext2(struct xar *xar, const char *name) { const char *flag = NULL; if (strcmp(name, "SecureDeletion") == 0) { xar->xmlsts = FILE_EXT2_SecureDeletion; flag = "securedeletion"; } else if (strcmp(name, "Undelete") == 0) { xar->xmlsts = FILE_EXT2_Undelete; flag = "nouunlink"; } else if (strcmp(name, "Compress") == 0) { xar->xmlsts = FILE_EXT2_Compress; flag = "compress"; } else if (strcmp(name, "Synchronous") == 0) { xar->xmlsts = FILE_EXT2_Synchronous; flag = "sync"; } else if (strcmp(name, "Immutable") == 0) { xar->xmlsts = FILE_EXT2_Immutable; flag = "simmutable"; } else if (strcmp(name, "AppendOnly") == 0) { xar->xmlsts = FILE_EXT2_AppendOnly; flag = "sappend"; } else if (strcmp(name, "NoDump") == 0) { xar->xmlsts = FILE_EXT2_NoDump; flag = "nodump"; } else if (strcmp(name, "NoAtime") == 0) { xar->xmlsts = FILE_EXT2_NoAtime; flag = "noatime"; } else if (strcmp(name, "CompDirty") == 0) { xar->xmlsts = FILE_EXT2_CompDirty; flag = "compdirty"; } else if (strcmp(name, "CompBlock") == 0) { xar->xmlsts = FILE_EXT2_CompBlock; flag = "comprblk"; } else if (strcmp(name, "NoCompBlock") == 0) { xar->xmlsts = FILE_EXT2_NoCompBlock; flag = "nocomprblk"; } else if (strcmp(name, "CompError") == 0) { xar->xmlsts = FILE_EXT2_CompError; flag = "comperr"; } else if (strcmp(name, "BTree") == 0) { xar->xmlsts = FILE_EXT2_BTree; flag = "btree"; } else if (strcmp(name, "HashIndexed") == 0) { xar->xmlsts = FILE_EXT2_HashIndexed; flag = "hashidx"; } else if (strcmp(name, "iMagic") == 0) { xar->xmlsts = FILE_EXT2_iMagic; flag = "imagic"; } else if (strcmp(name, "Journaled") == 0) { xar->xmlsts = FILE_EXT2_Journaled; flag = "journal"; } else if (strcmp(name, "NoTail") == 0) { xar->xmlsts = FILE_EXT2_NoTail; flag = "notail"; } else if (strcmp(name, "DirSync") == 0) { xar->xmlsts = FILE_EXT2_DirSync; flag = "dirsync"; } else if (strcmp(name, "TopDir") == 0) { xar->xmlsts = FILE_EXT2_TopDir; flag = "topdir"; } else if (strcmp(name, "Reserved") == 0) { xar->xmlsts = FILE_EXT2_Reserved; flag = "reserved"; } if (flag == NULL) return (0); if (archive_strlen(&(xar->file->fflags_text)) > 0) archive_strappend_char(&(xar->file->fflags_text), ','); archive_strcat(&(xar->file->fflags_text), flag); return (1); } #ifdef HAVE_LIBXML_XMLREADER_H static int xml2_xmlattr_setup(struct archive_read *a, struct xmlattr_list *list, xmlTextReaderPtr reader) { struct xmlattr *attr; int r; list->first = NULL; list->last = &(list->first); r = xmlTextReaderMoveToFirstAttribute(reader); while (r == 1) { attr = malloc(sizeof*(attr)); if (attr == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } attr->name = strdup( (const char *)xmlTextReaderConstLocalName(reader)); if (attr->name == NULL) { free(attr); archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } attr->value = strdup( (const char *)xmlTextReaderConstValue(reader)); if (attr->value == NULL) { free(attr->name); free(attr); archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } attr->next = NULL; *list->last = attr; list->last = &(attr->next); r = xmlTextReaderMoveToNextAttribute(reader); } return (r); } static int xml2_read_cb(void *context, char *buffer, int len) { struct archive_read *a; struct xar *xar; const void *d; size_t outbytes; size_t used = 0; int r; a = (struct archive_read *)context; xar = (struct xar *)(a->format->data); if (xar->toc_remaining <= 0) return (0); d = buffer; outbytes = len; r = rd_contents(a, &d, &outbytes, &used, xar->toc_remaining); if (r != ARCHIVE_OK) return (r); __archive_read_consume(a, used); xar->toc_remaining -= used; xar->offset += used; xar->toc_total += outbytes; PRINT_TOC(buffer, len); return ((int)outbytes); } static int xml2_close_cb(void *context) { (void)context; /* UNUSED */ return (0); } static void xml2_error_hdr(void *arg, const char *msg, xmlParserSeverities severity, xmlTextReaderLocatorPtr locator) { struct archive_read *a; (void)locator; /* UNUSED */ a = (struct archive_read *)arg; switch (severity) { case XML_PARSER_SEVERITY_VALIDITY_WARNING: case XML_PARSER_SEVERITY_WARNING: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "XML Parsing error: %s", msg); break; case XML_PARSER_SEVERITY_VALIDITY_ERROR: case XML_PARSER_SEVERITY_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "XML Parsing error: %s", msg); break; } } static int xml2_read_toc(struct archive_read *a) { xmlTextReaderPtr reader; struct xmlattr_list list; int r; reader = xmlReaderForIO(xml2_read_cb, xml2_close_cb, a, NULL, NULL, 0); if (reader == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory for xml parser"); return (ARCHIVE_FATAL); } xmlTextReaderSetErrorHandler(reader, xml2_error_hdr, a); while ((r = xmlTextReaderRead(reader)) == 1) { const char *name, *value; int type, empty; type = xmlTextReaderNodeType(reader); name = (const char *)xmlTextReaderConstLocalName(reader); switch (type) { case XML_READER_TYPE_ELEMENT: empty = xmlTextReaderIsEmptyElement(reader); r = xml2_xmlattr_setup(a, &list, reader); if (r == ARCHIVE_OK) r = xml_start(a, name, &list); xmlattr_cleanup(&list); if (r != ARCHIVE_OK) return (r); if (empty) xml_end(a, name); break; case XML_READER_TYPE_END_ELEMENT: xml_end(a, name); break; case XML_READER_TYPE_TEXT: value = (const char *)xmlTextReaderConstValue(reader); xml_data(a, value, strlen(value)); break; case XML_READER_TYPE_SIGNIFICANT_WHITESPACE: default: break; } if (r < 0) break; } xmlFreeTextReader(reader); xmlCleanupParser(); return ((r == 0)?ARCHIVE_OK:ARCHIVE_FATAL); } #elif defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) static int expat_xmlattr_setup(struct archive_read *a, struct xmlattr_list *list, const XML_Char **atts) { struct xmlattr *attr; char *name, *value; list->first = NULL; list->last = &(list->first); if (atts == NULL) return (ARCHIVE_OK); while (atts[0] != NULL && atts[1] != NULL) { attr = malloc(sizeof*(attr)); name = strdup(atts[0]); value = strdup(atts[1]); if (attr == NULL || name == NULL || value == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); free(attr); free(name); free(value); return (ARCHIVE_FATAL); } attr->name = name; attr->value = value; attr->next = NULL; *list->last = attr; list->last = &(attr->next); atts += 2; } return (ARCHIVE_OK); } static void expat_start_cb(void *userData, const XML_Char *name, const XML_Char **atts) { struct expat_userData *ud = (struct expat_userData *)userData; struct archive_read *a = ud->archive; struct xmlattr_list list; int r; r = expat_xmlattr_setup(a, &list, atts); if (r == ARCHIVE_OK) r = xml_start(a, (const char *)name, &list); xmlattr_cleanup(&list); ud->state = r; } static void expat_end_cb(void *userData, const XML_Char *name) { struct expat_userData *ud = (struct expat_userData *)userData; xml_end(ud->archive, (const char *)name); } static void expat_data_cb(void *userData, const XML_Char *s, int len) { struct expat_userData *ud = (struct expat_userData *)userData; xml_data(ud->archive, s, len); } static int expat_read_toc(struct archive_read *a) { struct xar *xar; XML_Parser parser; struct expat_userData ud; ud.state = ARCHIVE_OK; ud.archive = a; xar = (struct xar *)(a->format->data); /* Initialize XML Parser library. */ parser = XML_ParserCreate(NULL); if (parser == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory for xml parser"); return (ARCHIVE_FATAL); } XML_SetUserData(parser, &ud); XML_SetElementHandler(parser, expat_start_cb, expat_end_cb); XML_SetCharacterDataHandler(parser, expat_data_cb); xar->xmlsts = INIT; while (xar->toc_remaining && ud.state == ARCHIVE_OK) { enum XML_Status xr; const void *d; size_t outbytes; size_t used; int r; d = NULL; r = rd_contents(a, &d, &outbytes, &used, xar->toc_remaining); if (r != ARCHIVE_OK) return (r); xar->toc_remaining -= used; xar->offset += used; xar->toc_total += outbytes; PRINT_TOC(d, outbytes); xr = XML_Parse(parser, d, outbytes, xar->toc_remaining == 0); __archive_read_consume(a, used); if (xr == XML_STATUS_ERROR) { XML_ParserFree(parser); archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "XML Parsing failed"); return (ARCHIVE_FATAL); } } XML_ParserFree(parser); return (ud.state); } #endif /* defined(HAVE_BSDXML_H) || defined(HAVE_EXPAT_H) */ #endif /* Support xar format */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2777_0
crossvul-cpp_data_good_328_0
/* * Copyright (c) 2001 * Fortress Technologies, Inc. All rights reserved. * Charlie Lenahan (clenahan@fortresstech.com) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IEEE 802.11 printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "cpack.h" /* Lengths of 802.11 header components. */ #define IEEE802_11_FC_LEN 2 #define IEEE802_11_DUR_LEN 2 #define IEEE802_11_DA_LEN 6 #define IEEE802_11_SA_LEN 6 #define IEEE802_11_BSSID_LEN 6 #define IEEE802_11_RA_LEN 6 #define IEEE802_11_TA_LEN 6 #define IEEE802_11_ADDR1_LEN 6 #define IEEE802_11_SEQ_LEN 2 #define IEEE802_11_CTL_LEN 2 #define IEEE802_11_CARRIED_FC_LEN 2 #define IEEE802_11_HT_CONTROL_LEN 4 #define IEEE802_11_IV_LEN 3 #define IEEE802_11_KID_LEN 1 /* Frame check sequence length. */ #define IEEE802_11_FCS_LEN 4 /* Lengths of beacon components. */ #define IEEE802_11_TSTAMP_LEN 8 #define IEEE802_11_BCNINT_LEN 2 #define IEEE802_11_CAPINFO_LEN 2 #define IEEE802_11_LISTENINT_LEN 2 #define IEEE802_11_AID_LEN 2 #define IEEE802_11_STATUS_LEN 2 #define IEEE802_11_REASON_LEN 2 /* Length of previous AP in reassocation frame */ #define IEEE802_11_AP_LEN 6 #define T_MGMT 0x0 /* management */ #define T_CTRL 0x1 /* control */ #define T_DATA 0x2 /* data */ #define T_RESV 0x3 /* reserved */ #define ST_ASSOC_REQUEST 0x0 #define ST_ASSOC_RESPONSE 0x1 #define ST_REASSOC_REQUEST 0x2 #define ST_REASSOC_RESPONSE 0x3 #define ST_PROBE_REQUEST 0x4 #define ST_PROBE_RESPONSE 0x5 /* RESERVED 0x6 */ /* RESERVED 0x7 */ #define ST_BEACON 0x8 #define ST_ATIM 0x9 #define ST_DISASSOC 0xA #define ST_AUTH 0xB #define ST_DEAUTH 0xC #define ST_ACTION 0xD /* RESERVED 0xE */ /* RESERVED 0xF */ static const struct tok st_str[] = { { ST_ASSOC_REQUEST, "Assoc Request" }, { ST_ASSOC_RESPONSE, "Assoc Response" }, { ST_REASSOC_REQUEST, "ReAssoc Request" }, { ST_REASSOC_RESPONSE, "ReAssoc Response" }, { ST_PROBE_REQUEST, "Probe Request" }, { ST_PROBE_RESPONSE, "Probe Response" }, { ST_BEACON, "Beacon" }, { ST_ATIM, "ATIM" }, { ST_DISASSOC, "Disassociation" }, { ST_AUTH, "Authentication" }, { ST_DEAUTH, "DeAuthentication" }, { ST_ACTION, "Action" }, { 0, NULL } }; #define CTRL_CONTROL_WRAPPER 0x7 #define CTRL_BAR 0x8 #define CTRL_BA 0x9 #define CTRL_PS_POLL 0xA #define CTRL_RTS 0xB #define CTRL_CTS 0xC #define CTRL_ACK 0xD #define CTRL_CF_END 0xE #define CTRL_END_ACK 0xF static const struct tok ctrl_str[] = { { CTRL_CONTROL_WRAPPER, "Control Wrapper" }, { CTRL_BAR, "BAR" }, { CTRL_BA, "BA" }, { CTRL_PS_POLL, "Power Save-Poll" }, { CTRL_RTS, "Request-To-Send" }, { CTRL_CTS, "Clear-To-Send" }, { CTRL_ACK, "Acknowledgment" }, { CTRL_CF_END, "CF-End" }, { CTRL_END_ACK, "CF-End+CF-Ack" }, { 0, NULL } }; #define DATA_DATA 0x0 #define DATA_DATA_CF_ACK 0x1 #define DATA_DATA_CF_POLL 0x2 #define DATA_DATA_CF_ACK_POLL 0x3 #define DATA_NODATA 0x4 #define DATA_NODATA_CF_ACK 0x5 #define DATA_NODATA_CF_POLL 0x6 #define DATA_NODATA_CF_ACK_POLL 0x7 #define DATA_QOS_DATA 0x8 #define DATA_QOS_DATA_CF_ACK 0x9 #define DATA_QOS_DATA_CF_POLL 0xA #define DATA_QOS_DATA_CF_ACK_POLL 0xB #define DATA_QOS_NODATA 0xC #define DATA_QOS_CF_POLL_NODATA 0xE #define DATA_QOS_CF_ACK_POLL_NODATA 0xF /* * The subtype field of a data frame is, in effect, composed of 4 flag * bits - CF-Ack, CF-Poll, Null (means the frame doesn't actually have * any data), and QoS. */ #define DATA_FRAME_IS_CF_ACK(x) ((x) & 0x01) #define DATA_FRAME_IS_CF_POLL(x) ((x) & 0x02) #define DATA_FRAME_IS_NULL(x) ((x) & 0x04) #define DATA_FRAME_IS_QOS(x) ((x) & 0x08) /* * Bits in the frame control field. */ #define FC_VERSION(fc) ((fc) & 0x3) #define FC_TYPE(fc) (((fc) >> 2) & 0x3) #define FC_SUBTYPE(fc) (((fc) >> 4) & 0xF) #define FC_TO_DS(fc) ((fc) & 0x0100) #define FC_FROM_DS(fc) ((fc) & 0x0200) #define FC_MORE_FLAG(fc) ((fc) & 0x0400) #define FC_RETRY(fc) ((fc) & 0x0800) #define FC_POWER_MGMT(fc) ((fc) & 0x1000) #define FC_MORE_DATA(fc) ((fc) & 0x2000) #define FC_PROTECTED(fc) ((fc) & 0x4000) #define FC_ORDER(fc) ((fc) & 0x8000) struct mgmt_header_t { uint16_t fc; uint16_t duration; uint8_t da[IEEE802_11_DA_LEN]; uint8_t sa[IEEE802_11_SA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; uint16_t seq_ctrl; }; #define MGMT_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_DA_LEN+IEEE802_11_SA_LEN+\ IEEE802_11_BSSID_LEN+IEEE802_11_SEQ_LEN) #define CAPABILITY_ESS(cap) ((cap) & 0x0001) #define CAPABILITY_IBSS(cap) ((cap) & 0x0002) #define CAPABILITY_CFP(cap) ((cap) & 0x0004) #define CAPABILITY_CFP_REQ(cap) ((cap) & 0x0008) #define CAPABILITY_PRIVACY(cap) ((cap) & 0x0010) struct ssid_t { uint8_t element_id; uint8_t length; u_char ssid[33]; /* 32 + 1 for null */ }; struct rates_t { uint8_t element_id; uint8_t length; uint8_t rate[16]; }; struct challenge_t { uint8_t element_id; uint8_t length; uint8_t text[254]; /* 1-253 + 1 for null */ }; struct fh_t { uint8_t element_id; uint8_t length; uint16_t dwell_time; uint8_t hop_set; uint8_t hop_pattern; uint8_t hop_index; }; struct ds_t { uint8_t element_id; uint8_t length; uint8_t channel; }; struct cf_t { uint8_t element_id; uint8_t length; uint8_t count; uint8_t period; uint16_t max_duration; uint16_t dur_remaing; }; struct tim_t { uint8_t element_id; uint8_t length; uint8_t count; uint8_t period; uint8_t bitmap_control; uint8_t bitmap[251]; }; #define E_SSID 0 #define E_RATES 1 #define E_FH 2 #define E_DS 3 #define E_CF 4 #define E_TIM 5 #define E_IBSS 6 /* reserved 7 */ /* reserved 8 */ /* reserved 9 */ /* reserved 10 */ /* reserved 11 */ /* reserved 12 */ /* reserved 13 */ /* reserved 14 */ /* reserved 15 */ /* reserved 16 */ #define E_CHALLENGE 16 /* reserved 17 */ /* reserved 18 */ /* reserved 19 */ /* reserved 16 */ /* reserved 16 */ struct mgmt_body_t { uint8_t timestamp[IEEE802_11_TSTAMP_LEN]; uint16_t beacon_interval; uint16_t listen_interval; uint16_t status_code; uint16_t aid; u_char ap[IEEE802_11_AP_LEN]; uint16_t reason_code; uint16_t auth_alg; uint16_t auth_trans_seq_num; int challenge_present; struct challenge_t challenge; uint16_t capability_info; int ssid_present; struct ssid_t ssid; int rates_present; struct rates_t rates; int ds_present; struct ds_t ds; int cf_present; struct cf_t cf; int fh_present; struct fh_t fh; int tim_present; struct tim_t tim; }; struct ctrl_control_wrapper_hdr_t { uint16_t fc; uint16_t duration; uint8_t addr1[IEEE802_11_ADDR1_LEN]; uint16_t carried_fc[IEEE802_11_CARRIED_FC_LEN]; uint16_t ht_control[IEEE802_11_HT_CONTROL_LEN]; }; #define CTRL_CONTROL_WRAPPER_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_ADDR1_LEN+\ IEEE802_11_CARRIED_FC_LEN+\ IEEE802_11_HT_CONTROL_LEN) struct ctrl_rts_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; }; #define CTRL_RTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_TA_LEN) struct ctrl_cts_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_CTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_ack_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_ps_poll_hdr_t { uint16_t fc; uint16_t aid; uint8_t bssid[IEEE802_11_BSSID_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; }; #define CTRL_PS_POLL_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_AID_LEN+\ IEEE802_11_BSSID_LEN+IEEE802_11_TA_LEN) struct ctrl_end_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; }; #define CTRL_END_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN) struct ctrl_end_ack_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t bssid[IEEE802_11_BSSID_LEN]; }; #define CTRL_END_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN) struct ctrl_ba_hdr_t { uint16_t fc; uint16_t duration; uint8_t ra[IEEE802_11_RA_LEN]; }; #define CTRL_BA_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN) struct ctrl_bar_hdr_t { uint16_t fc; uint16_t dur; uint8_t ra[IEEE802_11_RA_LEN]; uint8_t ta[IEEE802_11_TA_LEN]; uint16_t ctl; uint16_t seq; }; #define CTRL_BAR_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\ IEEE802_11_RA_LEN+IEEE802_11_TA_LEN+\ IEEE802_11_CTL_LEN+IEEE802_11_SEQ_LEN) struct meshcntl_t { uint8_t flags; uint8_t ttl; uint8_t seq[4]; uint8_t addr4[6]; uint8_t addr5[6]; uint8_t addr6[6]; }; #define IV_IV(iv) ((iv) & 0xFFFFFF) #define IV_PAD(iv) (((iv) >> 24) & 0x3F) #define IV_KEYID(iv) (((iv) >> 30) & 0x03) #define PRINT_SSID(p) \ if (p.ssid_present) { \ ND_PRINT((ndo, " (")); \ fn_print(ndo, p.ssid.ssid, NULL); \ ND_PRINT((ndo, ")")); \ } #define PRINT_RATE(_sep, _r, _suf) \ ND_PRINT((ndo, "%s%2.1f%s", _sep, (.5 * ((_r) & 0x7f)), _suf)) #define PRINT_RATES(p) \ if (p.rates_present) { \ int z; \ const char *sep = " ["; \ for (z = 0; z < p.rates.length ; z++) { \ PRINT_RATE(sep, p.rates.rate[z], \ (p.rates.rate[z] & 0x80 ? "*" : "")); \ sep = " "; \ } \ if (p.rates.length != 0) \ ND_PRINT((ndo, " Mbit]")); \ } #define PRINT_DS_CHANNEL(p) \ if (p.ds_present) \ ND_PRINT((ndo, " CH: %u", p.ds.channel)); \ ND_PRINT((ndo, "%s", \ CAPABILITY_PRIVACY(p.capability_info) ? ", PRIVACY" : "")); #define MAX_MCS_INDEX 76 /* * Indices are: * * the MCS index (0-76); * * 0 for 20 MHz, 1 for 40 MHz; * * 0 for a long guard interval, 1 for a short guard interval. */ static const float ieee80211_float_htrates[MAX_MCS_INDEX+1][2][2] = { /* MCS 0 */ { /* 20 Mhz */ { 6.5, /* SGI */ 7.2, }, /* 40 Mhz */ { 13.5, /* SGI */ 15.0, }, }, /* MCS 1 */ { /* 20 Mhz */ { 13.0, /* SGI */ 14.4, }, /* 40 Mhz */ { 27.0, /* SGI */ 30.0, }, }, /* MCS 2 */ { /* 20 Mhz */ { 19.5, /* SGI */ 21.7, }, /* 40 Mhz */ { 40.5, /* SGI */ 45.0, }, }, /* MCS 3 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 4 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 5 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 6 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 7 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 8 */ { /* 20 Mhz */ { 13.0, /* SGI */ 14.4, }, /* 40 Mhz */ { 27.0, /* SGI */ 30.0, }, }, /* MCS 9 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 10 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 11 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 12 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 13 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 14 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 15 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 16 */ { /* 20 Mhz */ { 19.5, /* SGI */ 21.7, }, /* 40 Mhz */ { 40.5, /* SGI */ 45.0, }, }, /* MCS 17 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 18 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 19 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 20 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 21 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 22 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 23 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 24 */ { /* 20 Mhz */ { 26.0, /* SGI */ 28.9, }, /* 40 Mhz */ { 54.0, /* SGI */ 60.0, }, }, /* MCS 25 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 26 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 27 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 28 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 29 */ { /* 20 Mhz */ { 208.0, /* SGI */ 231.1, }, /* 40 Mhz */ { 432.0, /* SGI */ 480.0, }, }, /* MCS 30 */ { /* 20 Mhz */ { 234.0, /* SGI */ 260.0, }, /* 40 Mhz */ { 486.0, /* SGI */ 540.0, }, }, /* MCS 31 */ { /* 20 Mhz */ { 260.0, /* SGI */ 288.9, }, /* 40 Mhz */ { 540.0, /* SGI */ 600.0, }, }, /* MCS 32 */ { /* 20 Mhz */ { 0.0, /* SGI */ 0.0, }, /* not valid */ /* 40 Mhz */ { 6.0, /* SGI */ 6.7, }, }, /* MCS 33 */ { /* 20 Mhz */ { 39.0, /* SGI */ 43.3, }, /* 40 Mhz */ { 81.0, /* SGI */ 90.0, }, }, /* MCS 34 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 35 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 36 */ { /* 20 Mhz */ { 58.5, /* SGI */ 65.0, }, /* 40 Mhz */ { 121.5, /* SGI */ 135.0, }, }, /* MCS 37 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 38 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 39 */ { /* 20 Mhz */ { 52.0, /* SGI */ 57.8, }, /* 40 Mhz */ { 108.0, /* SGI */ 120.0, }, }, /* MCS 40 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 41 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 42 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 43 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 44 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 45 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 46 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 47 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 48 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 49 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 50 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 51 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 52 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 53 */ { /* 20 Mhz */ { 65.0, /* SGI */ 72.2, }, /* 40 Mhz */ { 135.0, /* SGI */ 150.0, }, }, /* MCS 54 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 55 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 56 */ { /* 20 Mhz */ { 78.0, /* SGI */ 86.7, }, /* 40 Mhz */ { 162.0, /* SGI */ 180.0, }, }, /* MCS 57 */ { /* 20 Mhz */ { 91.0, /* SGI */ 101.1, }, /* 40 Mhz */ { 189.0, /* SGI */ 210.0, }, }, /* MCS 58 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 59 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 60 */ { /* 20 Mhz */ { 104.0, /* SGI */ 115.6, }, /* 40 Mhz */ { 216.0, /* SGI */ 240.0, }, }, /* MCS 61 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 62 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 63 */ { /* 20 Mhz */ { 130.0, /* SGI */ 144.4, }, /* 40 Mhz */ { 270.0, /* SGI */ 300.0, }, }, /* MCS 64 */ { /* 20 Mhz */ { 143.0, /* SGI */ 158.9, }, /* 40 Mhz */ { 297.0, /* SGI */ 330.0, }, }, /* MCS 65 */ { /* 20 Mhz */ { 97.5, /* SGI */ 108.3, }, /* 40 Mhz */ { 202.5, /* SGI */ 225.0, }, }, /* MCS 66 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 67 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 68 */ { /* 20 Mhz */ { 117.0, /* SGI */ 130.0, }, /* 40 Mhz */ { 243.0, /* SGI */ 270.0, }, }, /* MCS 69 */ { /* 20 Mhz */ { 136.5, /* SGI */ 151.7, }, /* 40 Mhz */ { 283.5, /* SGI */ 315.0, }, }, /* MCS 70 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 71 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 72 */ { /* 20 Mhz */ { 156.0, /* SGI */ 173.3, }, /* 40 Mhz */ { 324.0, /* SGI */ 360.0, }, }, /* MCS 73 */ { /* 20 Mhz */ { 175.5, /* SGI */ 195.0, }, /* 40 Mhz */ { 364.5, /* SGI */ 405.0, }, }, /* MCS 74 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 75 */ { /* 20 Mhz */ { 195.0, /* SGI */ 216.7, }, /* 40 Mhz */ { 405.0, /* SGI */ 450.0, }, }, /* MCS 76 */ { /* 20 Mhz */ { 214.5, /* SGI */ 238.3, }, /* 40 Mhz */ { 445.5, /* SGI */ 495.0, }, }, }; static const char *auth_alg_text[]={"Open System","Shared Key","EAP"}; #define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0]) static const char *status_text[] = { "Successful", /* 0 */ "Unspecified failure", /* 1 */ "Reserved", /* 2 */ "Reserved", /* 3 */ "Reserved", /* 4 */ "Reserved", /* 5 */ "Reserved", /* 6 */ "Reserved", /* 7 */ "Reserved", /* 8 */ "Reserved", /* 9 */ "Cannot Support all requested capabilities in the Capability " "Information field", /* 10 */ "Reassociation denied due to inability to confirm that association " "exists", /* 11 */ "Association denied due to reason outside the scope of the " "standard", /* 12 */ "Responding station does not support the specified authentication " "algorithm ", /* 13 */ "Received an Authentication frame with authentication transaction " "sequence number out of expected sequence", /* 14 */ "Authentication rejected because of challenge failure", /* 15 */ "Authentication rejected due to timeout waiting for next frame in " "sequence", /* 16 */ "Association denied because AP is unable to handle additional" "associated stations", /* 17 */ "Association denied due to requesting station not supporting all of " "the data rates in BSSBasicRateSet parameter", /* 18 */ "Association denied due to requesting station not supporting " "short preamble operation", /* 19 */ "Association denied due to requesting station not supporting " "PBCC encoding", /* 20 */ "Association denied due to requesting station not supporting " "channel agility", /* 21 */ "Association request rejected because Spectrum Management " "capability is required", /* 22 */ "Association request rejected because the information in the " "Power Capability element is unacceptable", /* 23 */ "Association request rejected because the information in the " "Supported Channels element is unacceptable", /* 24 */ "Association denied due to requesting station not supporting " "short slot operation", /* 25 */ "Association denied due to requesting station not supporting " "DSSS-OFDM operation", /* 26 */ "Association denied because the requested STA does not support HT " "features", /* 27 */ "Reserved", /* 28 */ "Association denied because the requested STA does not support " "the PCO transition time required by the AP", /* 29 */ "Reserved", /* 30 */ "Reserved", /* 31 */ "Unspecified, QoS-related failure", /* 32 */ "Association denied due to QAP having insufficient bandwidth " "to handle another QSTA", /* 33 */ "Association denied due to excessive frame loss rates and/or " "poor conditions on current operating channel", /* 34 */ "Association (with QBSS) denied due to requesting station not " "supporting the QoS facility", /* 35 */ "Association denied due to requesting station not supporting " "Block Ack", /* 36 */ "The request has been declined", /* 37 */ "The request has not been successful as one or more parameters " "have invalid values", /* 38 */ "The TS has not been created because the request cannot be honored. " "Try again with the suggested changes to the TSPEC", /* 39 */ "Invalid Information Element", /* 40 */ "Group Cipher is not valid", /* 41 */ "Pairwise Cipher is not valid", /* 42 */ "AKMP is not valid", /* 43 */ "Unsupported RSN IE version", /* 44 */ "Invalid RSN IE Capabilities", /* 45 */ "Cipher suite is rejected per security policy", /* 46 */ "The TS has not been created. However, the HC may be capable of " "creating a TS, in response to a request, after the time indicated " "in the TS Delay element", /* 47 */ "Direct Link is not allowed in the BSS by policy", /* 48 */ "Destination STA is not present within this QBSS.", /* 49 */ "The Destination STA is not a QSTA.", /* 50 */ }; #define NUM_STATUSES (sizeof status_text / sizeof status_text[0]) static const char *reason_text[] = { "Reserved", /* 0 */ "Unspecified reason", /* 1 */ "Previous authentication no longer valid", /* 2 */ "Deauthenticated because sending station is leaving (or has left) " "IBSS or ESS", /* 3 */ "Disassociated due to inactivity", /* 4 */ "Disassociated because AP is unable to handle all currently " " associated stations", /* 5 */ "Class 2 frame received from nonauthenticated station", /* 6 */ "Class 3 frame received from nonassociated station", /* 7 */ "Disassociated because sending station is leaving " "(or has left) BSS", /* 8 */ "Station requesting (re)association is not authenticated with " "responding station", /* 9 */ "Disassociated because the information in the Power Capability " "element is unacceptable", /* 10 */ "Disassociated because the information in the SupportedChannels " "element is unacceptable", /* 11 */ "Invalid Information Element", /* 12 */ "Reserved", /* 13 */ "Michael MIC failure", /* 14 */ "4-Way Handshake timeout", /* 15 */ "Group key update timeout", /* 16 */ "Information element in 4-Way Handshake different from (Re)Association" "Request/Probe Response/Beacon", /* 17 */ "Group Cipher is not valid", /* 18 */ "AKMP is not valid", /* 20 */ "Unsupported RSN IE version", /* 21 */ "Invalid RSN IE Capabilities", /* 22 */ "IEEE 802.1X Authentication failed", /* 23 */ "Cipher suite is rejected per security policy", /* 24 */ "Reserved", /* 25 */ "Reserved", /* 26 */ "Reserved", /* 27 */ "Reserved", /* 28 */ "Reserved", /* 29 */ "Reserved", /* 30 */ "TS deleted because QoS AP lacks sufficient bandwidth for this " "QoS STA due to a change in BSS service characteristics or " "operational mode (e.g. an HT BSS change from 40 MHz channel " "to 20 MHz channel)", /* 31 */ "Disassociated for unspecified, QoS-related reason", /* 32 */ "Disassociated because QoS AP lacks sufficient bandwidth for this " "QoS STA", /* 33 */ "Disassociated because of excessive number of frames that need to be " "acknowledged, but are not acknowledged for AP transmissions " "and/or poor channel conditions", /* 34 */ "Disassociated because STA is transmitting outside the limits " "of its TXOPs", /* 35 */ "Requested from peer STA as the STA is leaving the BSS " "(or resetting)", /* 36 */ "Requested from peer STA as it does not want to use the " "mechanism", /* 37 */ "Requested from peer STA as the STA received frames using the " "mechanism for which a set up is required", /* 38 */ "Requested from peer STA due to time out", /* 39 */ "Reserved", /* 40 */ "Reserved", /* 41 */ "Reserved", /* 42 */ "Reserved", /* 43 */ "Reserved", /* 44 */ "Peer STA does not support the requested cipher suite", /* 45 */ "Association denied due to requesting STA not supporting HT " "features", /* 46 */ }; #define NUM_REASONS (sizeof reason_text / sizeof reason_text[0]) static int wep_print(netdissect_options *ndo, const u_char *p) { uint32_t iv; if (!ND_TTEST2(*p, IEEE802_11_IV_LEN + IEEE802_11_KID_LEN)) return 0; iv = EXTRACT_LE_32BITS(p); ND_PRINT((ndo, " IV:%3x Pad %x KeyID %x", IV_IV(iv), IV_PAD(iv), IV_KEYID(iv))); return 1; } static int parse_elements(netdissect_options *ndo, struct mgmt_body_t *pbody, const u_char *p, int offset, u_int length) { u_int elementlen; struct ssid_t ssid; struct challenge_t challenge; struct rates_t rates; struct ds_t ds; struct cf_t cf; struct tim_t tim; /* * We haven't seen any elements yet. */ pbody->challenge_present = 0; pbody->ssid_present = 0; pbody->rates_present = 0; pbody->ds_present = 0; pbody->cf_present = 0; pbody->tim_present = 0; while (length != 0) { /* Make sure we at least have the element ID and length. */ if (!ND_TTEST2(*(p + offset), 2)) return 0; if (length < 2) return 0; elementlen = *(p + offset + 1); /* Make sure we have the entire element. */ if (!ND_TTEST2(*(p + offset + 2), elementlen)) return 0; if (length < elementlen + 2) return 0; switch (*(p + offset)) { case E_SSID: memcpy(&ssid, p + offset, 2); offset += 2; length -= 2; if (ssid.length != 0) { if (ssid.length > sizeof(ssid.ssid) - 1) return 0; memcpy(&ssid.ssid, p + offset, ssid.length); offset += ssid.length; length -= ssid.length; } ssid.ssid[ssid.length] = '\0'; /* * Present and not truncated. * * If we haven't already seen an SSID IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->ssid_present) { pbody->ssid = ssid; pbody->ssid_present = 1; } break; case E_CHALLENGE: memcpy(&challenge, p + offset, 2); offset += 2; length -= 2; if (challenge.length != 0) { if (challenge.length > sizeof(challenge.text) - 1) return 0; memcpy(&challenge.text, p + offset, challenge.length); offset += challenge.length; length -= challenge.length; } challenge.text[challenge.length] = '\0'; /* * Present and not truncated. * * If we haven't already seen a challenge IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->challenge_present) { pbody->challenge = challenge; pbody->challenge_present = 1; } break; case E_RATES: memcpy(&rates, p + offset, 2); offset += 2; length -= 2; if (rates.length != 0) { if (rates.length > sizeof rates.rate) return 0; memcpy(&rates.rate, p + offset, rates.length); offset += rates.length; length -= rates.length; } /* * Present and not truncated. * * If we haven't already seen a rates IE, * copy this one if it's not zero-length, * otherwise ignore this one, so we later * report the first one we saw. * * We ignore zero-length rates IEs as some * devices seem to put a zero-length rates * IE, followed by an SSID IE, followed by * a non-zero-length rates IE into frames, * even though IEEE Std 802.11-2007 doesn't * seem to indicate that a zero-length rates * IE is valid. */ if (!pbody->rates_present && rates.length != 0) { pbody->rates = rates; pbody->rates_present = 1; } break; case E_DS: memcpy(&ds, p + offset, 2); offset += 2; length -= 2; if (ds.length != 1) { offset += ds.length; length -= ds.length; break; } ds.channel = *(p + offset); offset += 1; length -= 1; /* * Present and not truncated. * * If we haven't already seen a DS IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->ds_present) { pbody->ds = ds; pbody->ds_present = 1; } break; case E_CF: memcpy(&cf, p + offset, 2); offset += 2; length -= 2; if (cf.length != 6) { offset += cf.length; length -= cf.length; break; } memcpy(&cf.count, p + offset, 6); offset += 6; length -= 6; /* * Present and not truncated. * * If we haven't already seen a CF IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->cf_present) { pbody->cf = cf; pbody->cf_present = 1; } break; case E_TIM: memcpy(&tim, p + offset, 2); offset += 2; length -= 2; if (tim.length <= 3) { offset += tim.length; length -= tim.length; break; } if (tim.length - 3 > (int)sizeof tim.bitmap) return 0; memcpy(&tim.count, p + offset, 3); offset += 3; length -= 3; memcpy(tim.bitmap, p + offset, tim.length - 3); offset += tim.length - 3; length -= tim.length - 3; /* * Present and not truncated. * * If we haven't already seen a TIM IE, * copy this one, otherwise ignore this one, * so we later report the first one we saw. */ if (!pbody->tim_present) { pbody->tim = tim; pbody->tim_present = 1; } break; default: #if 0 ND_PRINT((ndo, "(1) unhandled element_id (%d) ", *(p + offset))); #endif offset += 2 + elementlen; length -= 2 + elementlen; break; } } /* No problems found. */ return 1; } /********************************************************************************* * Print Handle functions for the management frame types *********************************************************************************/ static int handle_beacon(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; length -= IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; length -= IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); ND_PRINT((ndo, " %s", CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS")); PRINT_DS_CHANNEL(pbody); return ret; } static int handle_assoc_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; length -= IEEE802_11_LISTENINT_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); return ret; } static int handle_assoc_response(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.status_code = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_STATUS_LEN; length -= IEEE802_11_STATUS_LEN; pbody.aid = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_AID_LEN; length -= IEEE802_11_AID_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); ND_PRINT((ndo, " AID(%x) :%s: %s", ((uint16_t)(pbody.aid << 2 )) >> 2 , CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "", (pbody.status_code < NUM_STATUSES ? status_text[pbody.status_code] : "n/a"))); return ret; } static int handle_reassoc_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN)) return 0; if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; length -= IEEE802_11_LISTENINT_LEN; memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN); offset += IEEE802_11_AP_LEN; length -= IEEE802_11_AP_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); ND_PRINT((ndo, " AP : %s", etheraddr_string(ndo, pbody.ap ))); return ret; } static int handle_reassoc_response(netdissect_options *ndo, const u_char *p, u_int length) { /* Same as a Association Reponse */ return handle_assoc_response(ndo, p, length); } static int handle_probe_request(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); return ret; } static int handle_probe_response(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; length -= IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; length -= IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; length -= IEEE802_11_CAPINFO_LEN; ret = parse_elements(ndo, &pbody, p, offset, length); PRINT_SSID(pbody); PRINT_RATES(pbody); PRINT_DS_CHANNEL(pbody); return ret; } static int handle_atim(void) { /* the frame body for ATIM is null. */ return 1; } static int handle_disassoc(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; if (length < IEEE802_11_REASON_LEN) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); ND_PRINT((ndo, ": %s", (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved")); return 1; } static int handle_auth(netdissect_options *ndo, const u_char *p, u_int length) { struct mgmt_body_t pbody; int offset = 0; int ret; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, 6)) return 0; if (length < 6) return 0; pbody.auth_alg = EXTRACT_LE_16BITS(p); offset += 2; length -= 2; pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset); offset += 2; length -= 2; pbody.status_code = EXTRACT_LE_16BITS(p + offset); offset += 2; length -= 2; ret = parse_elements(ndo, &pbody, p, offset, length); if ((pbody.auth_alg == 1) && ((pbody.auth_trans_seq_num == 2) || (pbody.auth_trans_seq_num == 3))) { ND_PRINT((ndo, " (%s)-%x [Challenge Text] %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, ((pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : ""))); return ret; } ND_PRINT((ndo, " (%s)-%x: %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, (pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : "")); return ret; } static int handle_deauth(netdissect_options *ndo, const uint8_t *src, const u_char *p, u_int length) { struct mgmt_body_t pbody; const char *reason = NULL; memset(&pbody, 0, sizeof(pbody)); if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; if (length < IEEE802_11_REASON_LEN) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); reason = (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved"; if (ndo->ndo_eflag) { ND_PRINT((ndo, ": %s", reason)); } else { ND_PRINT((ndo, " (%s): %s", etheraddr_string(ndo, src), reason)); } return 1; } #define PRINT_HT_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "TxChWidth")) : \ (v) == 1 ? ND_PRINT((ndo, "MIMOPwrSave")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_BA_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "ADDBA Request")) : \ (v) == 1 ? ND_PRINT((ndo, "ADDBA Response")) : \ (v) == 2 ? ND_PRINT((ndo, "DELBA")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHLINK_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Request")) : \ (v) == 1 ? ND_PRINT((ndo, "Report")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHPEERING_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Open")) : \ (v) == 1 ? ND_PRINT((ndo, "Confirm")) : \ (v) == 2 ? ND_PRINT((ndo, "Close")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESHPATH_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Request")) : \ (v) == 1 ? ND_PRINT((ndo, "Report")) : \ (v) == 2 ? ND_PRINT((ndo, "Error")) : \ (v) == 3 ? ND_PRINT((ndo, "RootAnnouncement")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MESH_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "MeshLink")) : \ (v) == 1 ? ND_PRINT((ndo, "HWMP")) : \ (v) == 2 ? ND_PRINT((ndo, "Gate Announcement")) : \ (v) == 3 ? ND_PRINT((ndo, "Congestion Control")) : \ (v) == 4 ? ND_PRINT((ndo, "MCCA Setup Request")) : \ (v) == 5 ? ND_PRINT((ndo, "MCCA Setup Reply")) : \ (v) == 6 ? ND_PRINT((ndo, "MCCA Advertisement Request")) : \ (v) == 7 ? ND_PRINT((ndo, "MCCA Advertisement")) : \ (v) == 8 ? ND_PRINT((ndo, "MCCA Teardown")) : \ (v) == 9 ? ND_PRINT((ndo, "TBTT Adjustment Request")) : \ (v) == 10 ? ND_PRINT((ndo, "TBTT Adjustment Response")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_MULTIHOP_ACTION(v) (\ (v) == 0 ? ND_PRINT((ndo, "Proxy Update")) : \ (v) == 1 ? ND_PRINT((ndo, "Proxy Update Confirmation")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) #define PRINT_SELFPROT_ACTION(v) (\ (v) == 1 ? ND_PRINT((ndo, "Peering Open")) : \ (v) == 2 ? ND_PRINT((ndo, "Peering Confirm")) : \ (v) == 3 ? ND_PRINT((ndo, "Peering Close")) : \ (v) == 4 ? ND_PRINT((ndo, "Group Key Inform")) : \ (v) == 5 ? ND_PRINT((ndo, "Group Key Acknowledge")) : \ ND_PRINT((ndo, "Act#%d", (v))) \ ) static int handle_action(netdissect_options *ndo, const uint8_t *src, const u_char *p, u_int length) { if (!ND_TTEST2(*p, 2)) return 0; if (length < 2) return 0; if (ndo->ndo_eflag) { ND_PRINT((ndo, ": ")); } else { ND_PRINT((ndo, " (%s): ", etheraddr_string(ndo, src))); } switch (p[0]) { case 0: ND_PRINT((ndo, "Spectrum Management Act#%d", p[1])); break; case 1: ND_PRINT((ndo, "QoS Act#%d", p[1])); break; case 2: ND_PRINT((ndo, "DLS Act#%d", p[1])); break; case 3: ND_PRINT((ndo, "BA ")); PRINT_BA_ACTION(p[1]); break; case 7: ND_PRINT((ndo, "HT ")); PRINT_HT_ACTION(p[1]); break; case 13: ND_PRINT((ndo, "MeshAction ")); PRINT_MESH_ACTION(p[1]); break; case 14: ND_PRINT((ndo, "MultiohopAction ")); PRINT_MULTIHOP_ACTION(p[1]); break; case 15: ND_PRINT((ndo, "SelfprotectAction ")); PRINT_SELFPROT_ACTION(p[1]); break; case 127: ND_PRINT((ndo, "Vendor Act#%d", p[1])); break; default: ND_PRINT((ndo, "Reserved(%d) Act#%d", p[0], p[1])); break; } return 1; } /********************************************************************************* * Print Body funcs *********************************************************************************/ static int mgmt_body_print(netdissect_options *ndo, uint16_t fc, const uint8_t *src, const u_char *p, u_int length) { ND_PRINT((ndo, "%s", tok2str(st_str, "Unhandled Management subtype(%x)", FC_SUBTYPE(fc)))); /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) return wep_print(ndo, p); switch (FC_SUBTYPE(fc)) { case ST_ASSOC_REQUEST: return handle_assoc_request(ndo, p, length); case ST_ASSOC_RESPONSE: return handle_assoc_response(ndo, p, length); case ST_REASSOC_REQUEST: return handle_reassoc_request(ndo, p, length); case ST_REASSOC_RESPONSE: return handle_reassoc_response(ndo, p, length); case ST_PROBE_REQUEST: return handle_probe_request(ndo, p, length); case ST_PROBE_RESPONSE: return handle_probe_response(ndo, p, length); case ST_BEACON: return handle_beacon(ndo, p, length); case ST_ATIM: return handle_atim(); case ST_DISASSOC: return handle_disassoc(ndo, p, length); case ST_AUTH: return handle_auth(ndo, p, length); case ST_DEAUTH: return handle_deauth(ndo, src, p, length); case ST_ACTION: return handle_action(ndo, src, p, length); default: return 1; } } /********************************************************************************* * Handles printing all the control frame types *********************************************************************************/ static int ctrl_body_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc)))); switch (FC_SUBTYPE(fc)) { case CTRL_CONTROL_WRAPPER: /* XXX - requires special handling */ break; case CTRL_BAR: if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ", etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq)))); break; case CTRL_BA: if (!ND_TTEST2(*p, CTRL_BA_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra))); break; case CTRL_PS_POLL: if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN)) return 0; ND_PRINT((ndo, " AID(%x)", EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid)))); break; case CTRL_RTS: if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " TA:%s ", etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta))); break; case CTRL_CTS: if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra))); break; case CTRL_ACK: if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra))); break; case CTRL_CF_END: if (!ND_TTEST2(*p, CTRL_END_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra))); break; case CTRL_END_ACK: if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN)) return 0; if (!ndo->ndo_eflag) ND_PRINT((ndo, " RA:%s ", etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra))); break; } return 1; } /* * Data Frame - Address field contents * * To Ds | From DS | Addr 1 | Addr 2 | Addr 3 | Addr 4 * 0 | 0 | DA | SA | BSSID | n/a * 0 | 1 | DA | BSSID | SA | n/a * 1 | 0 | BSSID | SA | DA | n/a * 1 | 1 | RA | TA | DA | SA */ /* * Function to get source and destination MAC addresses for a data frame. */ static void get_data_src_dst_mac(uint16_t fc, const u_char *p, const uint8_t **srcp, const uint8_t **dstp) { #define ADDR1 (p + 4) #define ADDR2 (p + 10) #define ADDR3 (p + 16) #define ADDR4 (p + 24) if (!FC_TO_DS(fc)) { if (!FC_FROM_DS(fc)) { /* not To DS and not From DS */ *srcp = ADDR2; *dstp = ADDR1; } else { /* not To DS and From DS */ *srcp = ADDR3; *dstp = ADDR1; } } else { if (!FC_FROM_DS(fc)) { /* From DS and not To DS */ *srcp = ADDR2; *dstp = ADDR3; } else { /* To DS and From DS */ *srcp = ADDR4; *dstp = ADDR3; } } #undef ADDR1 #undef ADDR2 #undef ADDR3 #undef ADDR4 } static void get_mgmt_src_dst_mac(const u_char *p, const uint8_t **srcp, const uint8_t **dstp) { const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p; if (srcp != NULL) *srcp = hp->sa; if (dstp != NULL) *dstp = hp->da; } /* * Print Header funcs */ static void data_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { u_int subtype = FC_SUBTYPE(fc); if (DATA_FRAME_IS_CF_ACK(subtype) || DATA_FRAME_IS_CF_POLL(subtype) || DATA_FRAME_IS_QOS(subtype)) { ND_PRINT((ndo, "CF ")); if (DATA_FRAME_IS_CF_ACK(subtype)) { if (DATA_FRAME_IS_CF_POLL(subtype)) ND_PRINT((ndo, "Ack/Poll")); else ND_PRINT((ndo, "Ack")); } else { if (DATA_FRAME_IS_CF_POLL(subtype)) ND_PRINT((ndo, "Poll")); } if (DATA_FRAME_IS_QOS(subtype)) ND_PRINT((ndo, "+QoS")); ND_PRINT((ndo, " ")); } #define ADDR1 (p + 4) #define ADDR2 (p + 10) #define ADDR3 (p + 16) #define ADDR4 (p + 24) if (!FC_TO_DS(fc) && !FC_FROM_DS(fc)) { ND_PRINT((ndo, "DA:%s SA:%s BSSID:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (!FC_TO_DS(fc) && FC_FROM_DS(fc)) { ND_PRINT((ndo, "DA:%s BSSID:%s SA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (FC_TO_DS(fc) && !FC_FROM_DS(fc)) { ND_PRINT((ndo, "BSSID:%s SA:%s DA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3))); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) { ND_PRINT((ndo, "RA:%s TA:%s DA:%s SA:%s ", etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2), etheraddr_string(ndo, ADDR3), etheraddr_string(ndo, ADDR4))); } #undef ADDR1 #undef ADDR2 #undef ADDR3 #undef ADDR4 } static void mgmt_header_print(netdissect_options *ndo, const u_char *p) { const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p; ND_PRINT((ndo, "BSSID:%s DA:%s SA:%s ", etheraddr_string(ndo, (hp)->bssid), etheraddr_string(ndo, (hp)->da), etheraddr_string(ndo, (hp)->sa))); } static void ctrl_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p) { switch (FC_SUBTYPE(fc)) { case CTRL_BAR: ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ", etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)), EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq)))); break; case CTRL_BA: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra))); break; case CTRL_PS_POLL: ND_PRINT((ndo, "BSSID:%s TA:%s ", etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->bssid), etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->ta))); break; case CTRL_RTS: ND_PRINT((ndo, "RA:%s TA:%s ", etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta))); break; case CTRL_CTS: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra))); break; case CTRL_ACK: ND_PRINT((ndo, "RA:%s ", etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra))); break; case CTRL_CF_END: ND_PRINT((ndo, "RA:%s BSSID:%s ", etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->bssid))); break; case CTRL_END_ACK: ND_PRINT((ndo, "RA:%s BSSID:%s ", etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra), etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->bssid))); break; default: /* We shouldn't get here - we should already have quit */ break; } } static int extract_header_length(netdissect_options *ndo, uint16_t fc) { int len; switch (FC_TYPE(fc)) { case T_MGMT: return MGMT_HDRLEN; case T_CTRL: switch (FC_SUBTYPE(fc)) { case CTRL_CONTROL_WRAPPER: return CTRL_CONTROL_WRAPPER_HDRLEN; case CTRL_BAR: return CTRL_BAR_HDRLEN; case CTRL_BA: return CTRL_BA_HDRLEN; case CTRL_PS_POLL: return CTRL_PS_POLL_HDRLEN; case CTRL_RTS: return CTRL_RTS_HDRLEN; case CTRL_CTS: return CTRL_CTS_HDRLEN; case CTRL_ACK: return CTRL_ACK_HDRLEN; case CTRL_CF_END: return CTRL_END_HDRLEN; case CTRL_END_ACK: return CTRL_END_ACK_HDRLEN; default: ND_PRINT((ndo, "unknown 802.11 ctrl frame subtype (%d)", FC_SUBTYPE(fc))); return 0; } case T_DATA: len = (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24; if (DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) len += 2; return len; default: ND_PRINT((ndo, "unknown 802.11 frame type (%d)", FC_TYPE(fc))); return 0; } } static int extract_mesh_header_length(const u_char *p) { return (p[0] &~ 3) ? 0 : 6*(1 + (p[0] & 3)); } /* * Print the 802.11 MAC header. */ static void ieee_802_11_hdr_print(netdissect_options *ndo, uint16_t fc, const u_char *p, u_int hdrlen, u_int meshdrlen) { if (ndo->ndo_vflag) { if (FC_MORE_DATA(fc)) ND_PRINT((ndo, "More Data ")); if (FC_MORE_FLAG(fc)) ND_PRINT((ndo, "More Fragments ")); if (FC_POWER_MGMT(fc)) ND_PRINT((ndo, "Pwr Mgmt ")); if (FC_RETRY(fc)) ND_PRINT((ndo, "Retry ")); if (FC_ORDER(fc)) ND_PRINT((ndo, "Strictly Ordered ")); if (FC_PROTECTED(fc)) ND_PRINT((ndo, "Protected ")); if (FC_TYPE(fc) != T_CTRL || FC_SUBTYPE(fc) != CTRL_PS_POLL) ND_PRINT((ndo, "%dus ", EXTRACT_LE_16BITS( &((const struct mgmt_header_t *)p)->duration))); } if (meshdrlen != 0) { const struct meshcntl_t *mc = (const struct meshcntl_t *)&p[hdrlen - meshdrlen]; int ae = mc->flags & 3; ND_PRINT((ndo, "MeshData (AE %d TTL %u seq %u", ae, mc->ttl, EXTRACT_LE_32BITS(mc->seq))); if (ae > 0) ND_PRINT((ndo, " A4:%s", etheraddr_string(ndo, mc->addr4))); if (ae > 1) ND_PRINT((ndo, " A5:%s", etheraddr_string(ndo, mc->addr5))); if (ae > 2) ND_PRINT((ndo, " A6:%s", etheraddr_string(ndo, mc->addr6))); ND_PRINT((ndo, ") ")); } switch (FC_TYPE(fc)) { case T_MGMT: mgmt_header_print(ndo, p); break; case T_CTRL: ctrl_header_print(ndo, fc, p); break; case T_DATA: data_header_print(ndo, fc, p); break; default: break; } } #ifndef roundup2 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ #endif static const char tstr[] = "[|802.11]"; static u_int ieee802_11_print(netdissect_options *ndo, const u_char *p, u_int length, u_int orig_caplen, int pad, u_int fcslen) { uint16_t fc; u_int caplen, hdrlen, meshdrlen; struct lladdr_info src, dst; int llc_hdrlen; caplen = orig_caplen; /* Remove FCS, if present */ if (length < fcslen) { ND_PRINT((ndo, "%s", tstr)); return caplen; } length -= fcslen; if (caplen > length) { /* Amount of FCS in actual packet data, if any */ fcslen = caplen - length; caplen -= fcslen; ndo->ndo_snapend -= fcslen; } if (caplen < IEEE802_11_FC_LEN) { ND_PRINT((ndo, "%s", tstr)); return orig_caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(ndo, fc); if (hdrlen == 0) { /* Unknown frame type or control frame subtype; quit. */ return (0); } if (pad) hdrlen = roundup2(hdrlen, 4); if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA && DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) { if (caplen < hdrlen + 1) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } meshdrlen = extract_mesh_header_length(p+hdrlen); hdrlen += meshdrlen; } else meshdrlen = 0; if (caplen < hdrlen) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } if (ndo->ndo_eflag) ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen); /* * Go past the 802.11 header. */ length -= hdrlen; caplen -= hdrlen; p += hdrlen; src.addr_string = etheraddr_string; dst.addr_string = etheraddr_string; switch (FC_TYPE(fc)) { case T_MGMT: get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr); if (!mgmt_body_print(ndo, fc, src.addr, p, length)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_CTRL: if (!ctrl_body_print(ndo, fc, p - hdrlen)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_DATA: if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc))) return hdrlen; /* no-data frame */ /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) { ND_PRINT((ndo, "Data")); if (!wep_print(ndo, p)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } } else { get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr); llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* * Some kinds of LLC packet we cannot * handle intelligently */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } break; default: /* We shouldn't get here - we should already have quit */ break; } return hdrlen; } /* * This is the top level routine of the printer. 'p' points * to the 802.11 header of the packet, 'h->ts' is the timestamp, * 'h->len' is the length of the packet off the wire, and 'h->caplen' * is the number of bytes actually captured. */ u_int ieee802_11_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_print(ndo, p, h->len, h->caplen, 0, 0); } /* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */ /* NetBSD: ieee802_11_radio.h,v 1.2 2006/02/26 03:04:03 dyoung Exp */ /*- * Copyright (c) 2003, 2004 David Young. 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. The name of David Young may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``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 DAVID * YOUNG 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. */ /* A generic radio capture format is desirable. It must be * rigidly defined (e.g., units for fields should be given), * and easily extensible. * * The following is an extensible radio capture format. It is * based on a bitmap indicating which fields are present. * * I am trying to describe precisely what the application programmer * should expect in the following, and for that reason I tell the * units and origin of each measurement (where it applies), or else I * use sufficiently weaselly language ("is a monotonically nondecreasing * function of...") that I cannot set false expectations for lawyerly * readers. */ /* * The radio capture header precedes the 802.11 header. * * Note well: all radiotap fields are little-endian. */ struct ieee80211_radiotap_header { uint8_t it_version; /* Version 0. Only increases * for drastic changes, * introduction of compatible * new fields does not count. */ uint8_t it_pad; uint16_t it_len; /* length of the whole * header in bytes, including * it_version, it_pad, * it_len, and data fields. */ uint32_t it_present; /* A bitmap telling which * fields are present. Set bit 31 * (0x80000000) to extend the * bitmap by another 32 bits. * Additional extensions are made * by setting bit 31. */ }; /* Name Data type Units * ---- --------- ----- * * IEEE80211_RADIOTAP_TSFT uint64_t microseconds * * Value in microseconds of the MAC's 64-bit 802.11 Time * Synchronization Function timer when the first bit of the * MPDU arrived at the MAC. For received frames, only. * * IEEE80211_RADIOTAP_CHANNEL 2 x uint16_t MHz, bitmap * * Tx/Rx frequency in MHz, followed by flags (see below). * Note that IEEE80211_RADIOTAP_XCHANNEL must be used to * represent an HT channel as there is not enough room in * the flags word. * * IEEE80211_RADIOTAP_FHSS uint16_t see below * * For frequency-hopping radios, the hop set (first byte) * and pattern (second byte). * * IEEE80211_RADIOTAP_RATE uint8_t 500kb/s or index * * Tx/Rx data rate. If bit 0x80 is set then it represents an * an MCS index and not an IEEE rate. * * IEEE80211_RADIOTAP_DBM_ANTSIGNAL int8_t decibels from * one milliwatt (dBm) * * RF signal power at the antenna, decibel difference from * one milliwatt. * * IEEE80211_RADIOTAP_DBM_ANTNOISE int8_t decibels from * one milliwatt (dBm) * * RF noise power at the antenna, decibel difference from one * milliwatt. * * IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB) * * RF signal power at the antenna, decibel difference from an * arbitrary, fixed reference. * * IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB) * * RF noise power at the antenna, decibel difference from an * arbitrary, fixed reference point. * * IEEE80211_RADIOTAP_LOCK_QUALITY uint16_t unitless * * Quality of Barker code lock. Unitless. Monotonically * nondecreasing with "better" lock strength. Called "Signal * Quality" in datasheets. (Is there a standard way to measure * this?) * * IEEE80211_RADIOTAP_TX_ATTENUATION uint16_t unitless * * Transmit power expressed as unitless distance from max * power set at factory calibration. 0 is max power. * Monotonically nondecreasing with lower power levels. * * IEEE80211_RADIOTAP_DB_TX_ATTENUATION uint16_t decibels (dB) * * Transmit power expressed as decibel distance from max power * set at factory calibration. 0 is max power. Monotonically * nondecreasing with lower power levels. * * IEEE80211_RADIOTAP_DBM_TX_POWER int8_t decibels from * one milliwatt (dBm) * * Transmit power expressed as dBm (decibels from a 1 milliwatt * reference). This is the absolute power level measured at * the antenna port. * * IEEE80211_RADIOTAP_FLAGS uint8_t bitmap * * Properties of transmitted and received frames. See flags * defined below. * * IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index * * Unitless indication of the Rx/Tx antenna for this packet. * The first antenna is antenna 0. * * IEEE80211_RADIOTAP_RX_FLAGS uint16_t bitmap * * Properties of received frames. See flags defined below. * * IEEE80211_RADIOTAP_XCHANNEL uint32_t bitmap * uint16_t MHz * uint8_t channel number * uint8_t .5 dBm * * Extended channel specification: flags (see below) followed by * frequency in MHz, the corresponding IEEE channel number, and * finally the maximum regulatory transmit power cap in .5 dBm * units. This property supersedes IEEE80211_RADIOTAP_CHANNEL * and only one of the two should be present. * * IEEE80211_RADIOTAP_MCS uint8_t known * uint8_t flags * uint8_t mcs * * Bitset indicating which fields have known values, followed * by bitset of flag values, followed by the MCS rate index as * in IEEE 802.11n. * * * IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitless * * Contains the AMPDU information for the subframe. * * IEEE80211_RADIOTAP_VHT u16, u8, u8, u8[4], u8, u8, u16 * * Contains VHT information about this frame. * * IEEE80211_RADIOTAP_VENDOR_NAMESPACE * uint8_t OUI[3] * uint8_t subspace * uint16_t length * * The Vendor Namespace Field contains three sub-fields. The first * sub-field is 3 bytes long. It contains the vendor's IEEE 802 * Organizationally Unique Identifier (OUI). The fourth byte is a * vendor-specific "namespace selector." * */ enum ieee80211_radiotap_type { IEEE80211_RADIOTAP_TSFT = 0, IEEE80211_RADIOTAP_FLAGS = 1, IEEE80211_RADIOTAP_RATE = 2, IEEE80211_RADIOTAP_CHANNEL = 3, IEEE80211_RADIOTAP_FHSS = 4, IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5, IEEE80211_RADIOTAP_DBM_ANTNOISE = 6, IEEE80211_RADIOTAP_LOCK_QUALITY = 7, IEEE80211_RADIOTAP_TX_ATTENUATION = 8, IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9, IEEE80211_RADIOTAP_DBM_TX_POWER = 10, IEEE80211_RADIOTAP_ANTENNA = 11, IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12, IEEE80211_RADIOTAP_DB_ANTNOISE = 13, IEEE80211_RADIOTAP_RX_FLAGS = 14, /* NB: gap for netbsd definitions */ IEEE80211_RADIOTAP_XCHANNEL = 18, IEEE80211_RADIOTAP_MCS = 19, IEEE80211_RADIOTAP_AMPDU_STATUS = 20, IEEE80211_RADIOTAP_VHT = 21, IEEE80211_RADIOTAP_NAMESPACE = 29, IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30, IEEE80211_RADIOTAP_EXT = 31 }; /* channel attributes */ #define IEEE80211_CHAN_TURBO 0x00010 /* Turbo channel */ #define IEEE80211_CHAN_CCK 0x00020 /* CCK channel */ #define IEEE80211_CHAN_OFDM 0x00040 /* OFDM channel */ #define IEEE80211_CHAN_2GHZ 0x00080 /* 2 GHz spectrum channel. */ #define IEEE80211_CHAN_5GHZ 0x00100 /* 5 GHz spectrum channel */ #define IEEE80211_CHAN_PASSIVE 0x00200 /* Only passive scan allowed */ #define IEEE80211_CHAN_DYN 0x00400 /* Dynamic CCK-OFDM channel */ #define IEEE80211_CHAN_GFSK 0x00800 /* GFSK channel (FHSS PHY) */ #define IEEE80211_CHAN_GSM 0x01000 /* 900 MHz spectrum channel */ #define IEEE80211_CHAN_STURBO 0x02000 /* 11a static turbo channel only */ #define IEEE80211_CHAN_HALF 0x04000 /* Half rate channel */ #define IEEE80211_CHAN_QUARTER 0x08000 /* Quarter rate channel */ #define IEEE80211_CHAN_HT20 0x10000 /* HT 20 channel */ #define IEEE80211_CHAN_HT40U 0x20000 /* HT 40 channel w/ ext above */ #define IEEE80211_CHAN_HT40D 0x40000 /* HT 40 channel w/ ext below */ /* Useful combinations of channel characteristics, borrowed from Ethereal */ #define IEEE80211_CHAN_A \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_B \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK) #define IEEE80211_CHAN_G \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN) #define IEEE80211_CHAN_TA \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_TURBO) #define IEEE80211_CHAN_TG \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN | IEEE80211_CHAN_TURBO) /* For IEEE80211_RADIOTAP_FLAGS */ #define IEEE80211_RADIOTAP_F_CFP 0x01 /* sent/received * during CFP */ #define IEEE80211_RADIOTAP_F_SHORTPRE 0x02 /* sent/received * with short * preamble */ #define IEEE80211_RADIOTAP_F_WEP 0x04 /* sent/received * with WEP encryption */ #define IEEE80211_RADIOTAP_F_FRAG 0x08 /* sent/received * with fragmentation */ #define IEEE80211_RADIOTAP_F_FCS 0x10 /* frame includes FCS */ #define IEEE80211_RADIOTAP_F_DATAPAD 0x20 /* frame has padding between * 802.11 header and payload * (to 32-bit boundary) */ #define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* does not pass FCS check */ /* For IEEE80211_RADIOTAP_RX_FLAGS */ #define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */ #define IEEE80211_RADIOTAP_F_RX_PLCP_CRC 0x0002 /* frame failed PLCP CRC check */ /* For IEEE80211_RADIOTAP_MCS known */ #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN 0x01 #define IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN 0x02 /* MCS index field */ #define IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN 0x04 #define IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN 0x08 #define IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN 0x10 #define IEEE80211_RADIOTAP_MCS_STBC_KNOWN 0x20 #define IEEE80211_RADIOTAP_MCS_NESS_KNOWN 0x40 #define IEEE80211_RADIOTAP_MCS_NESS_BIT_1 0x80 /* For IEEE80211_RADIOTAP_MCS flags */ #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK 0x03 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20 0 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 1 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20L 2 #define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20U 3 #define IEEE80211_RADIOTAP_MCS_SHORT_GI 0x04 /* short guard interval */ #define IEEE80211_RADIOTAP_MCS_HT_GREENFIELD 0x08 #define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10 #define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60 #define IEEE80211_RADIOTAP_MCS_STBC_1 1 #define IEEE80211_RADIOTAP_MCS_STBC_2 2 #define IEEE80211_RADIOTAP_MCS_STBC_3 3 #define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5 #define IEEE80211_RADIOTAP_MCS_NESS_BIT_0 0x80 /* For IEEE80211_RADIOTAP_AMPDU_STATUS */ #define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001 #define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002 #define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004 #define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008 #define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010 #define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020 /* For IEEE80211_RADIOTAP_VHT known */ #define IEEE80211_RADIOTAP_VHT_STBC_KNOWN 0x0001 #define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA_KNOWN 0x0002 #define IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN 0x0004 #define IEEE80211_RADIOTAP_VHT_SGI_NSYM_DIS_KNOWN 0x0008 #define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM_KNOWN 0x0010 #define IEEE80211_RADIOTAP_VHT_BEAMFORMED_KNOWN 0x0020 #define IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN 0x0040 #define IEEE80211_RADIOTAP_VHT_GROUP_ID_KNOWN 0x0080 #define IEEE80211_RADIOTAP_VHT_PARTIAL_AID_KNOWN 0x0100 /* For IEEE80211_RADIOTAP_VHT flags */ #define IEEE80211_RADIOTAP_VHT_STBC 0x01 #define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA 0x02 #define IEEE80211_RADIOTAP_VHT_SHORT_GI 0x04 #define IEEE80211_RADIOTAP_VHT_SGI_NSYM_M10_9 0x08 #define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM 0x10 #define IEEE80211_RADIOTAP_VHT_BEAMFORMED 0x20 #define IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK 0x1f #define IEEE80211_RADIOTAP_VHT_NSS_MASK 0x0f #define IEEE80211_RADIOTAP_VHT_MCS_MASK 0xf0 #define IEEE80211_RADIOTAP_VHT_MCS_SHIFT 4 #define IEEE80211_RADIOTAP_CODING_LDPC_USERn 0x01 #define IEEE80211_CHAN_FHSS \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK) #define IEEE80211_CHAN_A \ (IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_B \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK) #define IEEE80211_CHAN_PUREG \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM) #define IEEE80211_CHAN_G \ (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN) #define IS_CHAN_FHSS(flags) \ ((flags & IEEE80211_CHAN_FHSS) == IEEE80211_CHAN_FHSS) #define IS_CHAN_A(flags) \ ((flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A) #define IS_CHAN_B(flags) \ ((flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B) #define IS_CHAN_PUREG(flags) \ ((flags & IEEE80211_CHAN_PUREG) == IEEE80211_CHAN_PUREG) #define IS_CHAN_G(flags) \ ((flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G) #define IS_CHAN_ANYG(flags) \ (IS_CHAN_PUREG(flags) || IS_CHAN_G(flags)) static void print_chaninfo(netdissect_options *ndo, uint16_t freq, int flags, int presentflags) { ND_PRINT((ndo, "%u MHz", freq)); if (presentflags & (1 << IEEE80211_RADIOTAP_MCS)) { /* * We have the MCS field, so this is 11n, regardless * of what the channel flags say. */ ND_PRINT((ndo, " 11n")); } else { if (IS_CHAN_FHSS(flags)) ND_PRINT((ndo, " FHSS")); if (IS_CHAN_A(flags)) { if (flags & IEEE80211_CHAN_HALF) ND_PRINT((ndo, " 11a/10Mhz")); else if (flags & IEEE80211_CHAN_QUARTER) ND_PRINT((ndo, " 11a/5Mhz")); else ND_PRINT((ndo, " 11a")); } if (IS_CHAN_ANYG(flags)) { if (flags & IEEE80211_CHAN_HALF) ND_PRINT((ndo, " 11g/10Mhz")); else if (flags & IEEE80211_CHAN_QUARTER) ND_PRINT((ndo, " 11g/5Mhz")); else ND_PRINT((ndo, " 11g")); } else if (IS_CHAN_B(flags)) ND_PRINT((ndo, " 11b")); if (flags & IEEE80211_CHAN_TURBO) ND_PRINT((ndo, " Turbo")); } /* * These apply to 11n. */ if (flags & IEEE80211_CHAN_HT20) ND_PRINT((ndo, " ht/20")); else if (flags & IEEE80211_CHAN_HT40D) ND_PRINT((ndo, " ht/40-")); else if (flags & IEEE80211_CHAN_HT40U) ND_PRINT((ndo, " ht/40+")); ND_PRINT((ndo, " ")); } static int print_radiotap_field(netdissect_options *ndo, struct cpack_state *s, uint32_t bit, uint8_t *flagsp, uint32_t presentflags) { u_int i; int rc; switch (bit) { case IEEE80211_RADIOTAP_TSFT: { uint64_t tsft; rc = cpack_uint64(s, &tsft); if (rc != 0) goto trunc; ND_PRINT((ndo, "%" PRIu64 "us tsft ", tsft)); break; } case IEEE80211_RADIOTAP_FLAGS: { uint8_t flagsval; rc = cpack_uint8(s, &flagsval); if (rc != 0) goto trunc; *flagsp = flagsval; if (flagsval & IEEE80211_RADIOTAP_F_CFP) ND_PRINT((ndo, "cfp ")); if (flagsval & IEEE80211_RADIOTAP_F_SHORTPRE) ND_PRINT((ndo, "short preamble ")); if (flagsval & IEEE80211_RADIOTAP_F_WEP) ND_PRINT((ndo, "wep ")); if (flagsval & IEEE80211_RADIOTAP_F_FRAG) ND_PRINT((ndo, "fragmented ")); if (flagsval & IEEE80211_RADIOTAP_F_BADFCS) ND_PRINT((ndo, "bad-fcs ")); break; } case IEEE80211_RADIOTAP_RATE: { uint8_t rate; rc = cpack_uint8(s, &rate); if (rc != 0) goto trunc; /* * XXX On FreeBSD rate & 0x80 means we have an MCS. On * Linux and AirPcap it does not. (What about * Mac OS X, NetBSD, OpenBSD, and DragonFly BSD?) * * This is an issue either for proprietary extensions * to 11a or 11g, which do exist, or for 11n * implementations that stuff a rate value into * this field, which also appear to exist. * * We currently handle that by assuming that * if the 0x80 bit is set *and* the remaining * bits have a value between 0 and 15 it's * an MCS value, otherwise it's a rate. If * there are cases where systems that use * "0x80 + MCS index" for MCS indices > 15, * or stuff a rate value here between 64 and * 71.5 Mb/s in here, we'll need a preference * setting. Such rates do exist, e.g. 11n * MCS 7 at 20 MHz with a long guard interval. */ if (rate >= 0x80 && rate <= 0x8f) { /* * XXX - we don't know the channel width * or guard interval length, so we can't * convert this to a data rate. * * If you want us to show a data rate, * use the MCS field, not the Rate field; * the MCS field includes not only the * MCS index, it also includes bandwidth * and guard interval information. * * XXX - can we get the channel width * from XChannel and the guard interval * information from Flags, at least on * FreeBSD? */ ND_PRINT((ndo, "MCS %u ", rate & 0x7f)); } else ND_PRINT((ndo, "%2.1f Mb/s ", .5 * rate)); break; } case IEEE80211_RADIOTAP_CHANNEL: { uint16_t frequency; uint16_t flags; rc = cpack_uint16(s, &frequency); if (rc != 0) goto trunc; rc = cpack_uint16(s, &flags); if (rc != 0) goto trunc; /* * If CHANNEL and XCHANNEL are both present, skip * CHANNEL. */ if (presentflags & (1 << IEEE80211_RADIOTAP_XCHANNEL)) break; print_chaninfo(ndo, frequency, flags, presentflags); break; } case IEEE80211_RADIOTAP_FHSS: { uint8_t hopset; uint8_t hoppat; rc = cpack_uint8(s, &hopset); if (rc != 0) goto trunc; rc = cpack_uint8(s, &hoppat); if (rc != 0) goto trunc; ND_PRINT((ndo, "fhset %d fhpat %d ", hopset, hoppat)); break; } case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: { int8_t dbm_antsignal; rc = cpack_int8(s, &dbm_antsignal); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm signal ", dbm_antsignal)); break; } case IEEE80211_RADIOTAP_DBM_ANTNOISE: { int8_t dbm_antnoise; rc = cpack_int8(s, &dbm_antnoise); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm noise ", dbm_antnoise)); break; } case IEEE80211_RADIOTAP_LOCK_QUALITY: { uint16_t lock_quality; rc = cpack_uint16(s, &lock_quality); if (rc != 0) goto trunc; ND_PRINT((ndo, "%u sq ", lock_quality)); break; } case IEEE80211_RADIOTAP_TX_ATTENUATION: { uint16_t tx_attenuation; rc = cpack_uint16(s, &tx_attenuation); if (rc != 0) goto trunc; ND_PRINT((ndo, "%d tx power ", -(int)tx_attenuation)); break; } case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: { uint8_t db_tx_attenuation; rc = cpack_uint8(s, &db_tx_attenuation); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB tx attenuation ", -(int)db_tx_attenuation)); break; } case IEEE80211_RADIOTAP_DBM_TX_POWER: { int8_t dbm_tx_power; rc = cpack_int8(s, &dbm_tx_power); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddBm tx power ", dbm_tx_power)); break; } case IEEE80211_RADIOTAP_ANTENNA: { uint8_t antenna; rc = cpack_uint8(s, &antenna); if (rc != 0) goto trunc; ND_PRINT((ndo, "antenna %u ", antenna)); break; } case IEEE80211_RADIOTAP_DB_ANTSIGNAL: { uint8_t db_antsignal; rc = cpack_uint8(s, &db_antsignal); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB signal ", db_antsignal)); break; } case IEEE80211_RADIOTAP_DB_ANTNOISE: { uint8_t db_antnoise; rc = cpack_uint8(s, &db_antnoise); if (rc != 0) goto trunc; ND_PRINT((ndo, "%ddB noise ", db_antnoise)); break; } case IEEE80211_RADIOTAP_RX_FLAGS: { uint16_t rx_flags; rc = cpack_uint16(s, &rx_flags); if (rc != 0) goto trunc; /* Do nothing for now */ break; } case IEEE80211_RADIOTAP_XCHANNEL: { uint32_t flags; uint16_t frequency; uint8_t channel; uint8_t maxpower; rc = cpack_uint32(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint16(s, &frequency); if (rc != 0) goto trunc; rc = cpack_uint8(s, &channel); if (rc != 0) goto trunc; rc = cpack_uint8(s, &maxpower); if (rc != 0) goto trunc; print_chaninfo(ndo, frequency, flags, presentflags); break; } case IEEE80211_RADIOTAP_MCS: { uint8_t known; uint8_t flags; uint8_t mcs_index; static const char *ht_bandwidth[4] = { "20 MHz", "40 MHz", "20 MHz (L)", "20 MHz (U)" }; float htrate; rc = cpack_uint8(s, &known); if (rc != 0) goto trunc; rc = cpack_uint8(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &mcs_index); if (rc != 0) goto trunc; if (known & IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN) { /* * We know the MCS index. */ if (mcs_index <= MAX_MCS_INDEX) { /* * And it's in-range. */ if (known & (IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN|IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN)) { /* * And we know both the bandwidth and * the guard interval, so we can look * up the rate. */ htrate = ieee80211_float_htrates \ [mcs_index] \ [((flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK) == IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 ? 1 : 0)] \ [((flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? 1 : 0)]; } else { /* * We don't know both the bandwidth * and the guard interval, so we can * only report the MCS index. */ htrate = 0.0; } } else { /* * The MCS value is out of range. */ htrate = 0.0; } if (htrate != 0.0) { /* * We have the rate. * Print it. */ ND_PRINT((ndo, "%.1f Mb/s MCS %u ", htrate, mcs_index)); } else { /* * We at least have the MCS index. * Print it. */ ND_PRINT((ndo, "MCS %u ", mcs_index)); } } if (known & IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN) { ND_PRINT((ndo, "%s ", ht_bandwidth[flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK])); } if (known & IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN) { ND_PRINT((ndo, "%s GI ", (flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? "short" : "long")); } if (known & IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN) { ND_PRINT((ndo, "%s ", (flags & IEEE80211_RADIOTAP_MCS_HT_GREENFIELD) ? "greenfield" : "mixed")); } if (known & IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN) { ND_PRINT((ndo, "%s FEC ", (flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC) ? "LDPC" : "BCC")); } if (known & IEEE80211_RADIOTAP_MCS_STBC_KNOWN) { ND_PRINT((ndo, "RX-STBC%u ", (flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >> IEEE80211_RADIOTAP_MCS_STBC_SHIFT)); } break; } case IEEE80211_RADIOTAP_AMPDU_STATUS: { uint32_t reference_num; uint16_t flags; uint8_t delim_crc; uint8_t reserved; rc = cpack_uint32(s, &reference_num); if (rc != 0) goto trunc; rc = cpack_uint16(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &delim_crc); if (rc != 0) goto trunc; rc = cpack_uint8(s, &reserved); if (rc != 0) goto trunc; /* Do nothing for now */ break; } case IEEE80211_RADIOTAP_VHT: { uint16_t known; uint8_t flags; uint8_t bandwidth; uint8_t mcs_nss[4]; uint8_t coding; uint8_t group_id; uint16_t partial_aid; static const char *vht_bandwidth[32] = { "20 MHz", "40 MHz", "20 MHz (L)", "20 MHz (U)", "80 MHz", "80 MHz (L)", "80 MHz (U)", "80 MHz (LL)", "80 MHz (LU)", "80 MHz (UL)", "80 MHz (UU)", "160 MHz", "160 MHz (L)", "160 MHz (U)", "160 MHz (LL)", "160 MHz (LU)", "160 MHz (UL)", "160 MHz (UU)", "160 MHz (LLL)", "160 MHz (LLU)", "160 MHz (LUL)", "160 MHz (UUU)", "160 MHz (ULL)", "160 MHz (ULU)", "160 MHz (UUL)", "160 MHz (UUU)", "unknown (26)", "unknown (27)", "unknown (28)", "unknown (29)", "unknown (30)", "unknown (31)" }; rc = cpack_uint16(s, &known); if (rc != 0) goto trunc; rc = cpack_uint8(s, &flags); if (rc != 0) goto trunc; rc = cpack_uint8(s, &bandwidth); if (rc != 0) goto trunc; for (i = 0; i < 4; i++) { rc = cpack_uint8(s, &mcs_nss[i]); if (rc != 0) goto trunc; } rc = cpack_uint8(s, &coding); if (rc != 0) goto trunc; rc = cpack_uint8(s, &group_id); if (rc != 0) goto trunc; rc = cpack_uint16(s, &partial_aid); if (rc != 0) goto trunc; for (i = 0; i < 4; i++) { u_int nss, mcs; nss = mcs_nss[i] & IEEE80211_RADIOTAP_VHT_NSS_MASK; mcs = (mcs_nss[i] & IEEE80211_RADIOTAP_VHT_MCS_MASK) >> IEEE80211_RADIOTAP_VHT_MCS_SHIFT; if (nss == 0) continue; ND_PRINT((ndo, "User %u MCS %u ", i, mcs)); ND_PRINT((ndo, "%s FEC ", (coding & (IEEE80211_RADIOTAP_CODING_LDPC_USERn << i)) ? "LDPC" : "BCC")); } if (known & IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN) { ND_PRINT((ndo, "%s ", vht_bandwidth[bandwidth & IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK])); } if (known & IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN) { ND_PRINT((ndo, "%s GI ", (flags & IEEE80211_RADIOTAP_VHT_SHORT_GI) ? "short" : "long")); } break; } default: /* this bit indicates a field whose * size we do not know, so we cannot * proceed. Just print the bit number. */ ND_PRINT((ndo, "[bit %u] ", bit)); return -1; } return 0; trunc: ND_PRINT((ndo, "%s", tstr)); return rc; } static int print_in_radiotap_namespace(netdissect_options *ndo, struct cpack_state *s, uint8_t *flags, uint32_t presentflags, int bit0) { #define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x))) #define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x))) #define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x))) #define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x))) #define BITNO_2(x) (((x) & 2) ? 1 : 0) uint32_t present, next_present; int bitno; enum ieee80211_radiotap_type bit; int rc; for (present = presentflags; present; present = next_present) { /* * Clear the least significant bit that is set. */ next_present = present & (present - 1); /* * Get the bit number, within this presence word, * of the remaining least significant bit that * is set. */ bitno = BITNO_32(present ^ next_present); /* * Stop if this is one of the "same meaning * in all presence flags" bits. */ if (bitno >= IEEE80211_RADIOTAP_NAMESPACE) break; /* * Get the radiotap bit number of that bit. */ bit = (enum ieee80211_radiotap_type)(bit0 + bitno); rc = print_radiotap_field(ndo, s, bit, flags, presentflags); if (rc != 0) return rc; } return 0; } u_int ieee802_11_radio_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen) { #define BIT(n) (1U << n) #define IS_EXTENDED(__p) \ (EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0 struct cpack_state cpacker; const struct ieee80211_radiotap_header *hdr; uint32_t presentflags; const uint32_t *presentp, *last_presentp; int vendor_namespace; uint8_t vendor_oui[3]; uint8_t vendor_subnamespace; uint16_t skip_length; int bit0; u_int len; uint8_t flags; int pad; u_int fcslen; if (caplen < sizeof(*hdr)) { ND_PRINT((ndo, "%s", tstr)); return caplen; } hdr = (const struct ieee80211_radiotap_header *)p; len = EXTRACT_LE_16BITS(&hdr->it_len); if (len < sizeof(*hdr)) { /* * The length is the length of the entire header, so * it must be as large as the fixed-length part of * the header. */ ND_PRINT((ndo, "%s", tstr)); return caplen; } /* * If we don't have the entire radiotap header, just give up. */ if (caplen < len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } cpack_init(&cpacker, (const uint8_t *)hdr, len); /* align against header start */ cpack_advance(&cpacker, sizeof(*hdr)); /* includes the 1st bitmap */ for (last_presentp = &hdr->it_present; (const u_char*)(last_presentp + 1) <= p + len && IS_EXTENDED(last_presentp); last_presentp++) cpack_advance(&cpacker, sizeof(hdr->it_present)); /* more bitmaps */ /* are there more bitmap extensions than bytes in header? */ if ((const u_char*)(last_presentp + 1) > p + len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } /* * Start out at the beginning of the default radiotap namespace. */ bit0 = 0; vendor_namespace = 0; memset(vendor_oui, 0, 3); vendor_subnamespace = 0; skip_length = 0; /* Assume no flags */ flags = 0; /* Assume no Atheros padding between 802.11 header and body */ pad = 0; /* Assume no FCS at end of frame */ fcslen = 0; for (presentp = &hdr->it_present; presentp <= last_presentp; presentp++) { presentflags = EXTRACT_LE_32BITS(presentp); /* * If this is a vendor namespace, we don't handle it. */ if (vendor_namespace) { /* * Skip past the stuff we don't understand. * If we add support for any vendor namespaces, * it'd be added here; use vendor_oui and * vendor_subnamespace to interpret the fields. */ if (cpack_advance(&cpacker, skip_length) != 0) { /* * Ran out of space in the packet. */ break; } /* * We've skipped it all; nothing more to * skip. */ skip_length = 0; } else { if (print_in_radiotap_namespace(ndo, &cpacker, &flags, presentflags, bit0) != 0) { /* * Fatal error - can't process anything * more in the radiotap header. */ break; } } /* * Handle the namespace switch bits; we've already handled * the extension bit in all but the last word above. */ switch (presentflags & (BIT(IEEE80211_RADIOTAP_NAMESPACE)|BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE))) { case 0: /* * We're not changing namespaces. * advance to the next 32 bits in the current * namespace. */ bit0 += 32; break; case BIT(IEEE80211_RADIOTAP_NAMESPACE): /* * We're switching to the radiotap namespace. * Reset the presence-bitmap index to 0, and * reset the namespace to the default radiotap * namespace. */ bit0 = 0; vendor_namespace = 0; memset(vendor_oui, 0, 3); vendor_subnamespace = 0; skip_length = 0; break; case BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE): /* * We're switching to a vendor namespace. * Reset the presence-bitmap index to 0, * note that we're in a vendor namespace, * and fetch the fields of the Vendor Namespace * item. */ bit0 = 0; vendor_namespace = 1; if ((cpack_align_and_reserve(&cpacker, 2)) == NULL) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[0]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[1]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_oui[2]) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint8(&cpacker, &vendor_subnamespace) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } if (cpack_uint16(&cpacker, &skip_length) != 0) { ND_PRINT((ndo, "%s", tstr)); break; } break; default: /* * Illegal combination. The behavior in this * case is undefined by the radiotap spec; we * just ignore both bits. */ break; } } if (flags & IEEE80211_RADIOTAP_F_DATAPAD) pad = 1; /* Atheros padding */ if (flags & IEEE80211_RADIOTAP_F_FCS) fcslen = 4; /* FCS at end of packet */ return len + ieee802_11_print(ndo, p + len, length - len, caplen - len, pad, fcslen); #undef BITNO_32 #undef BITNO_16 #undef BITNO_8 #undef BITNO_4 #undef BITNO_2 #undef BIT } static u_int ieee802_11_avs_radio_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen) { uint32_t caphdr_len; if (caplen < 8) { ND_PRINT((ndo, "%s", tstr)); return caplen; } caphdr_len = EXTRACT_32BITS(p + 4); if (caphdr_len < 8) { /* * Yow! The capture header length is claimed not * to be large enough to include even the version * cookie or capture header length! */ ND_PRINT((ndo, "%s", tstr)); return caplen; } if (caplen < caphdr_len) { ND_PRINT((ndo, "%s", tstr)); return caplen; } return caphdr_len + ieee802_11_print(ndo, p + caphdr_len, length - caphdr_len, caplen - caphdr_len, 0, 0); } #define PRISM_HDR_LEN 144 #define WLANCAP_MAGIC_COOKIE_BASE 0x80211000 #define WLANCAP_MAGIC_COOKIE_V1 0x80211001 #define WLANCAP_MAGIC_COOKIE_V2 0x80211002 /* * For DLT_PRISM_HEADER; like DLT_IEEE802_11, but with an extra header, * containing information such as radio information, which we * currently ignore. * * If, however, the packet begins with WLANCAP_MAGIC_COOKIE_V1 or * WLANCAP_MAGIC_COOKIE_V2, it's really DLT_IEEE802_11_RADIO_AVS * (currently, on Linux, there's no ARPHRD_ type for * DLT_IEEE802_11_RADIO_AVS, as there is a ARPHRD_IEEE80211_PRISM * for DLT_PRISM_HEADER, so ARPHRD_IEEE80211_PRISM is used for * the AVS header, and the first 4 bytes of the header are used to * indicate whether it's a Prism header or an AVS header). */ u_int prism_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t msgcode; if (caplen < 4) { ND_PRINT((ndo, "%s", tstr)); return caplen; } msgcode = EXTRACT_32BITS(p); if (msgcode == WLANCAP_MAGIC_COOKIE_V1 || msgcode == WLANCAP_MAGIC_COOKIE_V2) return ieee802_11_avs_radio_print(ndo, p, length, caplen); if (caplen < PRISM_HDR_LEN) { ND_PRINT((ndo, "%s", tstr)); return caplen; } return PRISM_HDR_LEN + ieee802_11_print(ndo, p + PRISM_HDR_LEN, length - PRISM_HDR_LEN, caplen - PRISM_HDR_LEN, 0, 0); } /* * For DLT_IEEE802_11_RADIO; like DLT_IEEE802_11, but with an extra * header, containing information such as radio information. */ u_int ieee802_11_radio_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_radio_print(ndo, p, h->len, h->caplen); } /* * For DLT_IEEE802_11_RADIO_AVS; like DLT_IEEE802_11, but with an * extra header, containing information such as radio information, * which we currently ignore. */ u_int ieee802_11_radio_avs_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return ieee802_11_avs_radio_print(ndo, p, h->len, h->caplen); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_328_0
crossvul-cpp_data_good_767_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L OOO CCCC AAA L EEEEE % % L O O C A A L E % % L O O C AAAAA L EEE % % L O O C A A L E % % LLLLL OOO CCCC A A LLLLL EEEEE % % % % % % MagickCore Image Locale Methods % % % % Software Design % % Cristy % % July 2003 % % % % % % 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/blob.h" #include "MagickCore/client.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image-private.h" #include "MagickCore/linked-list.h" #include "MagickCore/locale_.h" #include "MagickCore/locale-private.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #if defined(MAGICKCORE_HAVE_NEWLOCALE) || defined(MAGICKCORE_WINDOWS_SUPPORT) # define MAGICKCORE_LOCALE_SUPPORT #endif #define LocaleFilename "locale.xml" /* Static declarations. */ static const char *LocaleMap = "<?xml version=\"1.0\"?>" "<localemap>" " <locale name=\"C\">" " <Exception>" " <Message name=\"\">" " </Message>" " </Exception>" " </locale>" "</localemap>"; #ifdef __VMS #define asciimap AsciiMap #endif #if !defined(MAGICKCORE_HAVE_STRCASECMP) || !defined(MAGICKCORE_HAVE_STRNCASECMP) static const unsigned char AsciiMap[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xc5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }; #endif static SemaphoreInfo *locale_semaphore = (SemaphoreInfo *) NULL; static SplayTreeInfo *locale_cache = (SplayTreeInfo *) NULL; #if defined(MAGICKCORE_LOCALE_SUPPORT) static volatile locale_t c_locale = (locale_t) NULL; #endif /* Forward declarations. */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *), LoadLocaleCache(SplayTreeInfo *,const char *,const char *,const char *, const size_t,ExceptionInfo *); #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCLocale() allocates the C locale object, or (locale_t) 0 with % errno set if it cannot be acquired. % % The format of the AcquireCLocale method is: % % locale_t AcquireCLocale(void) % */ static locale_t AcquireCLocale(void) { #if defined(MAGICKCORE_HAVE_NEWLOCALE) if (c_locale == (locale_t) NULL) c_locale=newlocale(LC_ALL_MASK,"C",(locale_t) 0); #elif defined(MAGICKCORE_WINDOWS_SUPPORT) && !defined(__MINGW32__) if (c_locale == (locale_t) NULL) c_locale=_create_locale(LC_ALL,"C"); #endif return(c_locale); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e L o c a l e S p l a y T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireLocaleSplayTree() caches one or more locale configurations which % provides a mapping between locale attributes and a locale tag. % % The format of the AcquireLocaleSplayTree method is: % % SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the font file tag. % % o locale: the actual locale. % % o exception: return any errors or warnings in this structure. % */ static void *DestroyLocaleNode(void *locale_info) { register LocaleInfo *p; p=(LocaleInfo *) locale_info; if (p->path != (char *) NULL) p->path=DestroyString(p->path); if (p->tag != (char *) NULL) p->tag=DestroyString(p->tag); if (p->message != (char *) NULL) p->message=DestroyString(p->message); return(RelinquishMagickMemory(p)); } static SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, const char *locale,ExceptionInfo *exception) { MagickStatusType status; SplayTreeInfo *cache; cache=NewSplayTree(CompareSplayTreeString,(void *(*)(void *)) NULL, DestroyLocaleNode); status=MagickTrue; #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) { const StringInfo *option; LinkedListInfo *options; options=GetLocaleOptions(filename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); if (GetNumberOfNodesInSplayTree(cache) == 0) { options=GetLocaleOptions("english.xml",exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); } } #endif if (GetNumberOfNodesInSplayTree(cache) == 0) status&=LoadLocaleCache(cache,LocaleMap,"built-in",locale,0, exception); return(cache); } #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCLocale() releases the resources allocated for a locale object % returned by a call to the AcquireCLocale() method. % % The format of the DestroyCLocale method is: % % void DestroyCLocale(void) % */ static void DestroyCLocale(void) { if (c_locale != (locale_t) NULL) freelocale(c_locale); c_locale=(locale_t) NULL; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyLocaleOptions() releases memory associated with an locale % messages. % % The format of the DestroyProfiles method is: % % LinkedListInfo *DestroyLocaleOptions(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *DestroyOptions(void *message) { return(DestroyStringInfo((StringInfo *) message)); } MagickExport LinkedListInfo *DestroyLocaleOptions(LinkedListInfo *messages) { assert(messages != (LinkedListInfo *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); return(DestroyLinkedList(messages,DestroyOptions)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleFile() prints formatted output of a variable argument list to a % file in the "C" locale. % % The format of the FormatLocaleFile method is: % % ssize_t FormatLocaleFile(FILE *file,const char *format,...) % % A description of each parameter follows. % % o file: the file. % % o format: A file describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleFileList(FILE *file, const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VFPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vfprintf_l(file,format,locale,operands); #else n=(ssize_t) vfprintf_l(file,locale,format,operands); #endif } #else #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vfprintf(file,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vfprintf(file,format,operands); #endif #endif return(n); } MagickExport ssize_t FormatLocaleFile(FILE *file, const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleFileList(file,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleString() prints formatted output of a variable argument list to % a string buffer in the "C" locale. % % The format of the FormatLocaleString method is: % % ssize_t FormatLocaleString(char *string,const size_t length, % const char *format,...) % % A description of each parameter follows. % % o string: FormatLocaleString() returns the formatted string in this % character buffer. % % o length: the maximum length of the string. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleStringList(char *magick_restrict string, const size_t length,const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VSNPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vsnprintf_l(string,length,format,locale,operands); #else n=(ssize_t) vsnprintf_l(string,length,locale,format,operands); #endif } #elif defined(MAGICKCORE_HAVE_VSNPRINTF) #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vsnprintf(string,length,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vsnprintf(string,length,format,operands); #endif #else n=(ssize_t) vsprintf(string,format,operands); #endif if (n < 0) string[length-1]='\0'; return(n); } MagickExport ssize_t FormatLocaleString(char *magick_restrict string, const size_t length,const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(string,length,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t L o c a l e I n f o _ % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfo_() searches the locale list for the specified tag and if % found returns attributes for that element. % % The format of the GetLocaleInfo method is: % % const LocaleInfo *GetLocaleInfo_(const char *tag, % ExceptionInfo *exception) % % A description of each parameter follows: % % o tag: the locale tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport const LocaleInfo *GetLocaleInfo_(const char *tag, ExceptionInfo *exception) { const LocaleInfo *locale_info; assert(exception != (ExceptionInfo *) NULL); if (IsLocaleTreeInstantiated(exception) == MagickFalse) return((const LocaleInfo *) NULL); LockSemaphoreInfo(locale_semaphore); if ((tag == (const char *) NULL) || (LocaleCompare(tag,"*") == 0)) { ResetSplayTreeIterator(locale_cache); locale_info=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } locale_info=(const LocaleInfo *) GetValueFromSplayTree(locale_cache,tag); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e I n f o L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfoList() returns any locale messages that match the % specified pattern. % % The format of the GetLocaleInfoList function is: % % const LocaleInfo **GetLocaleInfoList(const char *pattern, % size_t *number_messages,ExceptionInfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of locale messages in % the list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleInfoCompare(const void *x,const void *y) { const LocaleInfo **p, **q; p=(const LocaleInfo **) x, q=(const LocaleInfo **) y; if (LocaleCompare((*p)->path,(*q)->path) == 0) return(LocaleCompare((*p)->tag,(*q)->tag)); return(LocaleCompare((*p)->path,(*q)->path)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport const LocaleInfo **GetLocaleInfoList(const char *pattern, size_t *number_messages,ExceptionInfo *exception) { const LocaleInfo **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((const LocaleInfo **) NULL); messages=(const LocaleInfo **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (const LocaleInfo **) NULL) return((const LocaleInfo **) NULL); /* Generate locale list. */ LockSemaphoreInfo(locale_semaphore); ResetSplayTreeIterator(locale_cache); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=p; p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleInfoCompare); messages[i]=(LocaleInfo *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleList() returns any locale messages that match the specified % pattern. % % The format of the GetLocaleList function is: % % char **GetLocaleList(const char *pattern,size_t *number_messages, % Exceptioninfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of messages in the % list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleTagCompare(const void *x,const void *y) { register char **p, **q; p=(char **) x; q=(char **) y; return(LocaleCompare(*p,*q)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport char **GetLocaleList(const char *pattern,size_t *number_messages, ExceptionInfo *exception) { char **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((char **) NULL); messages=(char **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (char **) NULL) return((char **) NULL); LockSemaphoreInfo(locale_semaphore); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=ConstantString(p->tag); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleTagCompare); messages[i]=(char *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e M e s s a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleMessage() returns a message in the current locale that matches the % supplied tag. % % The format of the GetLocaleMessage method is: % % const char *GetLocaleMessage(const char *tag) % % A description of each parameter follows: % % o tag: Return a message that matches this tag in the current locale. % */ MagickExport const char *GetLocaleMessage(const char *tag) { char name[MagickLocaleExtent]; const LocaleInfo *locale_info; ExceptionInfo *exception; if ((tag == (const char *) NULL) || (*tag == '\0')) return(tag); exception=AcquireExceptionInfo(); (void) FormatLocaleString(name,MagickLocaleExtent,"%s/",tag); locale_info=GetLocaleInfo_(name,exception); exception=DestroyExceptionInfo(exception); if (locale_info != (const LocaleInfo *) NULL) return(locale_info->message); return(tag); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleOptions() returns any Magick configuration messages associated % with the specified filename. % % The format of the GetLocaleOptions method is: % % LinkedListInfo *GetLocaleOptions(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the locale file tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport LinkedListInfo *GetLocaleOptions(const char *filename, ExceptionInfo *exception) { char path[MagickPathExtent]; const char *element; LinkedListInfo *messages, *paths; StringInfo *xml; assert(filename != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename); assert(exception != (ExceptionInfo *) NULL); (void) CopyMagickString(path,filename,MagickPathExtent); /* Load XML from configuration files to linked-list. */ messages=NewLinkedList(0); paths=GetConfigurePaths(filename,exception); if (paths != (LinkedListInfo *) NULL) { ResetLinkedListIterator(paths); element=(const char *) GetNextValueInLinkedList(paths); while (element != (const char *) NULL) { (void) FormatLocaleString(path,MagickPathExtent,"%s%s",element, filename); (void) LogMagickEvent(LocaleEvent,GetMagickModule(), "Searching for locale file: \"%s\"",path); xml=ConfigureFileToStringInfo(path); if (xml != (StringInfo *) NULL) (void) AppendValueToLinkedList(messages,xml); element=(const char *) GetNextValueInLinkedList(paths); } paths=DestroyLinkedList(paths,RelinquishMagickMemory); } #if defined(MAGICKCORE_WINDOWS_SUPPORT) { char *blob; blob=(char *) NTResourceToBlob(filename); if (blob != (char *) NULL) { xml=AcquireStringInfo(0); SetStringInfoLength(xml,strlen(blob)+1); SetStringInfoDatum(xml,(const unsigned char *) blob); blob=(char *) RelinquishMagickMemory(blob); SetStringInfoPath(xml,filename); (void) AppendValueToLinkedList(messages,xml); } } #endif ResetLinkedListIterator(messages); return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleValue() returns the message associated with the locale info. % % The format of the GetLocaleValue method is: % % const char *GetLocaleValue(const LocaleInfo *locale_info) % % A description of each parameter follows: % % o locale_info: The locale info. % */ MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(locale_info != (LocaleInfo *) NULL); assert(locale_info->signature == MagickCoreSignature); return(locale_info->message); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s L o c a l e T r e e I n s t a n t i a t e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsLocaleTreeInstantiated() determines if the locale tree is instantiated. % If not, it instantiates the tree and returns it. % % The format of the IsLocaleInstantiated method is: % % MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) % % A description of each parameter follows. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) { if (locale_cache == (SplayTreeInfo *) NULL) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache == (SplayTreeInfo *) NULL) { char *locale; register const char *p; locale=(char *) NULL; p=setlocale(LC_CTYPE,(const char *) NULL); if (p != (const char *) NULL) locale=ConstantString(p); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_ALL"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_MESSAGES"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_CTYPE"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LANG"); if (locale == (char *) NULL) locale=ConstantString("C"); locale_cache=AcquireLocaleSplayTree(LocaleFilename,locale,exception); locale=DestroyString(locale); } UnlockSemaphoreInfo(locale_semaphore); } return(locale_cache != (SplayTreeInfo *) NULL ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n t e r p r e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretLocaleValue() interprets the string as a floating point number in % the "C" locale and returns its value as a double. If sentinal is not a null % pointer, the method also sets the value pointed by sentinal to point to the % first character after the number. % % The format of the InterpretLocaleValue method is: % % double InterpretLocaleValue(const char *value,char **sentinal) % % A description of each parameter follows: % % o value: the string value. % % o sentinal: if sentinal is not NULL, a pointer to the character after the % last character used in the conversion is stored in the location % referenced by sentinal. % */ MagickExport double InterpretLocaleValue(const char *magick_restrict string, char **magick_restrict sentinal) { char *q; double value; if ((*string == '0') && ((string[1] | 0x20)=='x')) value=(double) strtoul(string,&q,16); else { #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_STRTOD_L) locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) value=strtod(string,&q); else value=strtod_l(string,&q,locale); #else value=strtod(string,&q); #endif } if (sentinal != (char **) NULL) *sentinal=q; return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t L o c a l e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListLocaleInfo() lists the locale info to a file. % % The format of the ListLocaleInfo method is: % % MagickBooleanType ListLocaleInfo(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to a FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListLocaleInfo(FILE *file, ExceptionInfo *exception) { const char *path; const LocaleInfo **locale_info; register ssize_t i; size_t number_messages; if (file == (const FILE *) NULL) file=stdout; number_messages=0; locale_info=GetLocaleInfoList("*",&number_messages,exception); if (locale_info == (const LocaleInfo **) NULL) return(MagickFalse); path=(const char *) NULL; for (i=0; i < (ssize_t) number_messages; i++) { if (locale_info[i]->stealth != MagickFalse) continue; if ((path == (const char *) NULL) || (LocaleCompare(path,locale_info[i]->path) != 0)) { if (locale_info[i]->path != (char *) NULL) (void) FormatLocaleFile(file,"\nPath: %s\n\n",locale_info[i]->path); (void) FormatLocaleFile(file,"Tag/Message\n"); (void) FormatLocaleFile(file, "-------------------------------------------------" "------------------------------\n"); } path=locale_info[i]->path; (void) FormatLocaleFile(file,"%s\n",locale_info[i]->tag); if (locale_info[i]->message != (char *) NULL) (void) FormatLocaleFile(file," %s",locale_info[i]->message); (void) FormatLocaleFile(file,"\n"); } (void) fflush(file); locale_info=(const LocaleInfo **) RelinquishMagickMemory((void *) locale_info); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o a d L o c a l e C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LoadLocaleCache() loads the locale configurations which provides a mapping % between locale attributes and a locale name. % % The format of the LoadLocaleCache method is: % % MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, % const char *filename,const size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o xml: The locale list in XML format. % % o filename: The locale list filename. % % o depth: depth of <include /> statements. % % o exception: return any errors or warnings in this structure. % */ static void ChopLocaleComponents(char *path,const size_t components) { register char *p; ssize_t count; if (*path == '\0') return; p=path+strlen(path)-1; if (*p == '/') *p='\0'; for (count=0; (count < (ssize_t) components) && (p > path); p--) if (*p == '/') { *p='\0'; count++; } if (count < (ssize_t) components) *path='\0'; } static void LocaleFatalErrorHandler( const ExceptionType magick_unused(severity), const char *reason,const char *description) { magick_unreferenced(severity); if (reason == (char *) NULL) return; (void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason); if (description != (char *) NULL) (void) FormatLocaleFile(stderr," (%s)",description); (void) FormatLocaleFile(stderr,".\n"); (void) fflush(stderr); exit(1); } static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception) { char keyword[MagickLocaleExtent], message[MagickLocaleExtent], tag[MagickLocaleExtent], *token; const char *q; FatalErrorHandler fatal_handler; LocaleInfo *locale_info; MagickStatusType status; register char *p; size_t extent; /* Read the locale configure file. */ (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading locale configure file \"%s\" ...",filename); if (xml == (const char *) NULL) return(MagickFalse); status=MagickTrue; locale_info=(LocaleInfo *) NULL; *tag='\0'; *message='\0'; *keyword='\0'; fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler); token=AcquireString(xml); extent=strlen(token)+MagickPathExtent; for (q=(char *) xml; *q != '\0'; ) { /* Interpret XML. */ GetNextToken(q,&q,extent,token); if (*token == '\0') break; (void) CopyMagickString(keyword,token,MagickLocaleExtent); if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0) { /* Doctype element. */ while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleNCompare(keyword,"<!--",4) == 0) { /* Comment element. */ while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleCompare(keyword,"<include") == 0) { /* Include element. */ while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"locale") == 0) { if (LocaleCompare(locale,token) != 0) break; continue; } if (LocaleCompare(keyword,"file") == 0) { if (depth > MagickMaxRecursionDepth) (void) ThrowMagickException(exception,GetMagickModule(), ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token); else { char path[MagickPathExtent], *file_xml; *path='\0'; GetPathComponent(filename,HeadPath,path); if (*path != '\0') (void) ConcatenateMagickString(path,DirectorySeparator, MagickPathExtent); if (*token == *DirectorySeparator) (void) CopyMagickString(path,token,MagickPathExtent); else (void) ConcatenateMagickString(path,token,MagickPathExtent); file_xml=FileToXML(path,~0UL); if (file_xml != (char *) NULL) { status&=LoadLocaleCache(cache,file_xml,path,locale, depth+1,exception); file_xml=DestroyString(file_xml); } } } } continue; } if (LocaleCompare(keyword,"<locale") == 0) { /* Locale element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); } continue; } if (LocaleCompare(keyword,"</locale>") == 0) { ChopLocaleComponents(tag,1); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (LocaleCompare(keyword,"<localemap>") == 0) continue; if (LocaleCompare(keyword,"</localemap>") == 0) continue; if (LocaleCompare(keyword,"<message") == 0) { /* Message element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"name") == 0) { (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); } } for (p=(char *) q; (*q != '<') && (*q != '\0'); q++) ; while (isspace((int) ((unsigned char) *p)) != 0) p++; q--; while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p)) q--; (void) CopyMagickString(message,p,MagickMin((size_t) (q-p+2), MagickLocaleExtent)); locale_info=(LocaleInfo *) AcquireCriticalMemory(sizeof(*locale_info)); (void) memset(locale_info,0,sizeof(*locale_info)); locale_info->path=ConstantString(filename); locale_info->tag=ConstantString(tag); locale_info->message=ConstantString(message); locale_info->signature=MagickCoreSignature; status=AddValueToSplayTree(cache,locale_info->tag,locale_info); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", locale_info->tag); (void) ConcatenateMagickString(tag,message,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"\n",MagickLocaleExtent); q++; continue; } if (LocaleCompare(keyword,"</message>") == 0) { ChopLocaleComponents(tag,2); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (*keyword == '<') { /* Subpath element. */ if (*(keyword+1) == '?') continue; if (*(keyword+1) == '/') { ChopLocaleComponents(tag,1); if (*tag != '\0') (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } token[strlen(token)-1]='\0'; (void) CopyMagickString(token,token+1,MagickLocaleExtent); (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } GetNextToken(q,(const char **) NULL,extent,token); if (*token != '=') continue; } token=(char *) RelinquishMagickMemory(token); (void) SetFatalErrorHandler(fatal_handler); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % LocaleCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The format of the LocaleCompare method is: % % int LocaleCompare(const char *p,const char *q) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % */ MagickExport int LocaleCompare(const char *p,const char *q) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRCASECMP) return(strcasecmp(p,q)); #else { register int c, d; for ( ; ; ) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if ((c == 0) || (AsciiMap[c] != AsciiMap[d])) break; p++; q++; } return(AsciiMap[c]-(int) AsciiMap[d]); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLower() transforms all of the characters in the supplied % null-terminated string, changing all uppercase letters to lowercase. % % The format of the LocaleLower method is: % % void LocaleLower(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to lower-case Locale. % */ MagickExport void LocaleLower(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleLowercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLowercase() convert to lowercase. % % The format of the LocaleLowercase method is: % % void LocaleLowercase(const int c) % % A description of each parameter follows: % % o If c is a uppercase letter, return its lowercase equivalent. % */ MagickExport int LocaleLowercase(const int c) { if (c == EOF) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e N C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleNCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % % LocaleNCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The LocaleNCompare method makes the same comparison as LocaleCompare but % looks at a maximum of n bytes. Bytes following a null byte are not % compared. % % The format of the LocaleNCompare method is: % % int LocaleNCompare(const char *p,const char *q,const size_t n) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % % o length: the number of characters to compare in strings p and q. % */ MagickExport int LocaleNCompare(const char *p,const char *q,const size_t length) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRNCASECMP) return(strncasecmp(p,q,length)); #else { register int c, d; register size_t i; for (i=length; i != 0; i--) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if (AsciiMap[c] != AsciiMap[d]) return(AsciiMap[c]-(int) AsciiMap[d]); if (c == 0) return(0); p++; q++; } return(0); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUpper() transforms all of the characters in the supplied % null-terminated string, changing all lowercase letters to uppercase. % % The format of the LocaleUpper method is: % % void LocaleUpper(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to upper-case Locale. % */ MagickExport void LocaleUpper(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleUppercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUppercase() convert to uppercase. % % The format of the LocaleUppercase method is: % % void LocaleUppercase(const int c) % % A description of each parameter follows: % % o If c is a lowercase letter, return its uppercase equivalent. % */ MagickExport int LocaleUppercase(const int c) { if (c == EOF) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l((int) ((unsigned char) c),c_locale)); #endif return(toupper((int) ((unsigned char) c))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentGenesis() instantiates the locale component. % % The format of the LocaleComponentGenesis method is: % % MagickBooleanType LocaleComponentGenesis(void) % */ MagickPrivate MagickBooleanType LocaleComponentGenesis(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) locale_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentTerminus() destroys the locale component. % % The format of the LocaleComponentTerminus method is: % % LocaleComponentTerminus(void) % */ MagickPrivate void LocaleComponentTerminus(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache != (SplayTreeInfo *) NULL) locale_cache=DestroySplayTree(locale_cache); #if defined(MAGICKCORE_LOCALE_SUPPORT) DestroyCLocale(); #endif UnlockSemaphoreInfo(locale_semaphore); RelinquishSemaphoreInfo(&locale_semaphore); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_767_0
crossvul-cpp_data_bad_933_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite 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/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.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/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/memory_.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resample.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImage() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImage method is: % % MagickBooleanType CompositeImage(Image *image, % const Image *source_image,const CompositeOperator compose, % const MagickBooleanType clip_to_self,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the canvas image, modified by he composition % % o source_image: the source image. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o clip_to_self: set to MagickTrue to limit composition to area composed. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o exception: return any errors or warnings in this structure. % */ /* Composition based on the SVG specification: A Composition is defined by... Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc) Y = 1 for source preserved Z = 1 for canvas preserved Conversion to transparency (then optimized) Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) Where... Sca = Sc*Sa normalized Source color divided by Source alpha Dca = Dc*Da normalized Dest color divided by Dest alpha Dc' = Dca'/Da' the desired color value for this channel. Da' in in the follow formula as 'gamma' The resulting alpla value. Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in the following optimizations... gamma = Sa+Da-Sa*Da; gamma = 1 - QuantumScale*alpha * QuantumScale*beta; opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma The above SVG definitions also define that Mathematical Composition methods should use a 'Over' blending mode for Alpha Channel. It however was not applied for composition modes of 'Plus', 'Minus', the modulus versions of 'Add' and 'Subtract'. Mathematical operator changes to be applied from IM v6.7... 1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed 'ModulusAdd' and 'ModulusSubtract' for clarity. 2) All mathematical compositions work as per the SVG specification with regard to blending. This now includes 'ModulusAdd' and 'ModulusSubtract'. 3) When the special channel flag 'sync' (syncronize channel updates) is turned off (enabled by default) then mathematical compositions are only performed on the channels specified, and are applied independantally of each other. In other words the mathematics is performed as 'pure' mathematical operations, rather than as image operations. */ static void HCLComposite(const MagickRealType hue,const MagickRealType chroma, const MagickRealType luma,MagickRealType *red,MagickRealType *green, MagickRealType *blue) { MagickRealType b, c, g, h, m, r, x; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); *red=QuantumRange*(r+m); *green=QuantumRange*(g+m); *blue=QuantumRange*(b+m); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma, MagickRealType *luma) { MagickRealType b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (MagickRealType *) NULL); assert(chroma != (MagickRealType *) NULL); assert(luma != (MagickRealType *) NULL); r=red; g=green; b=blue; max=MagickMax(r,MagickMax(g,b)); c=max-(MagickRealType) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == max) h=fmod((g-b)/c+6.0,6.0); else if (green == max) h=((b-r)/c)+2.0; else if (blue == max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static MagickBooleanType CompositeOverImage(Image *image, const Image *source_image,const MagickBooleanType clip_to_self, const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *image_view, *source_view; const char *value; MagickBooleanType clamp, status; MagickOffsetType progress; ssize_t y; /* Composite image. */ status=MagickTrue; progress=0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, Sa, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); alpha=Sa+Da-Sa*Da; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((source_traits == UndefinedPixelTrait) && (channel != AlphaPixelChannel)) continue; if (channel == AlphaPixelChannel) { /* Set alpha channel. */ pixel=QuantumRange*alpha; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Sc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; gamma=PerceptibleReciprocal(alpha); pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } MagickExport MagickBooleanType CompositeImage(Image *image, const Image *composite,const CompositeOperator compose, const MagickBooleanType clip_to_self,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *source_view, *image_view; const char *value; GeometryInfo geometry_info; Image *canvas_image, *source_image; MagickBooleanType clamp, status; MagickOffsetType progress; MagickRealType amount, canvas_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite != (Image *) NULL); assert(composite->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); source_image=CloneImage(composite,0,0,MagickTrue,exception); if (source_image == (const Image *) NULL) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); (void) SetImageColorspace(source_image,image->colorspace,exception); if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp)) { status=CompositeOverImage(image,source_image,clip_to_self,x_offset, y_offset,exception); source_image=DestroyImage(source_image); return(status); } amount=0.5; canvas_image=(Image *) NULL; canvas_dissolve=1.0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); SetGeometryInfo(&geometry_info); percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if (traits == UndefinedPixelTrait) continue; if (source_traits != UndefinedPixelTrait) SetPixelChannel(image,channel,p[i],q); else if (channel == AlphaPixelChannel) SetPixelChannel(image,channel,OpaqueAlpha,q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case IntensityCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } SetPixelAlpha(image,clamp != MagickFalse ? ClampPixel(GetPixelIntensity(source_image,p)) : ClampToQuantum(GetPixelIntensity(source_image,p)),q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case CopyAlphaCompositeOp: case ChangeMaskCompositeOp: { /* Modify canvas outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); break; } case BlurCompositeOp: { CacheView *canvas_view; MagickRealType angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling. Blur Image dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ canvas_image=CloneImage(image,0,0,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (const char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidSetting","'%s' '%s'","compose:args",value); source_image=DestroyImage(source_image); canvas_image=DestroyImage(canvas_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=height=geometry_info.rho*2.0; if ((flags & HeightValue) != 0 ) height=geometry_info.sigma*2.0; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; /* rotate vectors if a rotation angle is given */ if ((flags & XValue) != 0 ) { MagickRealType angle; angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } /* Otherwise lets set a angle range and calculate in the loop */ angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, then restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* do the variable blurring of each pixel in image */ GetPixelInfo(image,&pixel); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } if (fabs((double) angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(source_image,p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } #if 0 if ( x == 10 && y == 60 ) { (void) fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",blur.x1, blur.x2,blur.y1, blur.y2); (void) fprintf(stderr, "scaled by=%lf,%lf\n",QuantumScale* GetPixelRed(p),QuantumScale*GetPixelGreen(p)); #endif ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(source_image,p), blur.y1*QuantumScale*GetPixelGreen(source_image,p), blur.x2*QuantumScale*GetPixelRed(source_image,p), blur.y2*QuantumScale*GetPixelGreen(source_image,p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel,exception); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); source_view=DestroyCacheView(source_view); canvas_view=DestroyCacheView(canvas_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *canvas_view; MagickRealType horizontal_scale, vertical_scale; PixelInfo pixel; PointInfo center, offset; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ canvas_image=CloneImage(image,0,0,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue | HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0; vertical_scale=(MagickRealType) (source_image->rows-1)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1)/2.0; vertical_scale=(MagickRealType) (image->rows-1)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(source_image->columns-1)/200.0; vertical_scale*=(source_image->rows-1)/200.0; } else { horizontal_scale*=(image->columns-1)/200.0; vertical_scale*=(image->rows-1)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) != 0) center.x=(MagickRealType) ((image->columns-1)/2.0); else center.x=(MagickRealType) (x_offset+(source_image->columns-1)/ 2.0); else if ((flags & AspectValue) != 0) center.x=geometry_info.xi; else center.x=(MagickRealType) (x_offset+geometry_info.xi); if ((flags & YValue) == 0) if ((flags & AspectValue) != 0) center.y=(MagickRealType) ((image->rows-1)/2.0); else center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0); else if ((flags & AspectValue) != 0) center.y=geometry_info.psi; else center.y=(MagickRealType) (y_offset+geometry_info.psi); } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } /* Displace the offset. */ offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0); offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0); status=InterpolatePixelInfo(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); if (status == MagickFalse) break; /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)* (QuantumScale*GetPixelAlpha(source_image,p)); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } if (x < (ssize_t) source_image->columns) break; sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } canvas_view=DestroyCacheView(canvas_view); source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { canvas_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; if ((canvas_dissolve-MagickEpsilon) < 0.0) canvas_dissolve=0.0; } break; } case BlendCompositeOp: { value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; } break; } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) (void) ParseGeometry(value,&geometry_info); break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; MagickRealType blue, chroma, green, hue, luma, red; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } hue=0.0; chroma=0.0; luma=0.0; GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, DcaDa, Sa, SaSca, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; switch (compose) { case AlphaCompositeOp: case ChangeMaskCompositeOp: case CopyAlphaCompositeOp: case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case OutCompositeOp: case SrcInCompositeOp: case SrcOutCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; break; } case ClearCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=0.0; break; } case BlendCompositeOp: case DissolveCompositeOp: { if (channel == AlphaPixelChannel) pixel=canvas_dissolve*GetPixelAlpha(source_image,source); else pixel=(MagickRealType) source[channel]; break; } default: { pixel=(MagickRealType) source[channel]; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); switch (compose) { case BumpmapCompositeOp: { alpha=GetPixelIntensity(source_image,p)*Sa; break; } case ColorBurnCompositeOp: case ColorDodgeCompositeOp: case DarkenCompositeOp: case DifferenceCompositeOp: case DivideDstCompositeOp: case DivideSrcCompositeOp: case ExclusionCompositeOp: case HardLightCompositeOp: case HardMixCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case LightenCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case ModulusAddCompositeOp: case ModulusSubtractCompositeOp: case MultiplyCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ScreenCompositeOp: case SoftLightCompositeOp: case VividLightCompositeOp: { alpha=RoundToUnity(Sa+Da-Sa*Da); break; } case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case SrcInCompositeOp: { alpha=Sa*Da; break; } case DissolveCompositeOp: { alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+ canvas_dissolve*Da; break; } case DstOverCompositeOp: case OverCompositeOp: case SrcOverCompositeOp: { alpha=Sa+Da-Sa*Da; break; } case DstOutCompositeOp: { alpha=Da*(1.0-Sa); break; } case OutCompositeOp: case SrcOutCompositeOp: { alpha=Sa*(1.0-Da); break; } case BlendCompositeOp: case PlusCompositeOp: { alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da); break; } case XorCompositeOp: { alpha=Sa+Da-2.0*Sa*Da; break; } default: { alpha=1.0; break; } } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: case SaturateCompositeOp: { GetPixelInfoPixel(source_image,p,&source_pixel); GetPixelInfoPixel(image,q,&canvas_pixel); break; } default: break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel, sans; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits = GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((channel == AlphaPixelChannel) && ((traits & UpdatePixelTrait) != 0)) { /* Set alpha channel. */ switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case CopyBlackCompositeOp: case CopyBlueCompositeOp: case CopyCyanCompositeOp: case CopyGreenCompositeOp: case CopyMagentaCompositeOp: case CopyRedCompositeOp: case CopyYellowCompositeOp: case SrcAtopCompositeOp: case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Da; break; } case ChangeMaskCompositeOp: { MagickBooleanType equivalent; if (Da < 0.5) { pixel=(MagickRealType) TransparentAlpha; break; } equivalent=IsFuzzyEquivalencePixel(source_image,p,image,q); if (equivalent != MagickFalse) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) OpaqueAlpha; break; } case ClearCompositeOp: { pixel=(MagickRealType) TransparentAlpha; break; } case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Da; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Sa; break; } if (Sa < Da) { pixel=QuantumRange*Da; break; } pixel=QuantumRange*Sa; break; } case CopyAlphaCompositeOp: { if (source_image->alpha_trait == UndefinedPixelTrait) pixel=GetPixelIntensity(source_image,p); else pixel=QuantumRange*Sa; break; } case CopyCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: case DstAtopCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sa; break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case DifferenceCompositeOp: { pixel=QuantumRange*fabs(Sa-Da); break; } case LightenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case ModulateCompositeOp: { pixel=QuantumRange*Da; break; } case MultiplyCompositeOp: { pixel=QuantumRange*Sa*Da; break; } case StereoCompositeOp: { pixel=QuantumRange*(Sa+Da)/2; break; } default: { pixel=QuantumRange*alpha; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } if (source_traits == UndefinedPixelTrait) continue; /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Dc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; SaSca=Sa*PerceptibleReciprocal(Sca); DcaDa=Dca*PerceptibleReciprocal(Da); switch (compose) { case DarkenCompositeOp: case LightenCompositeOp: case ModulusSubtractCompositeOp: { gamma=PerceptibleReciprocal(1.0-alpha); break; } default: { gamma=PerceptibleReciprocal(alpha); break; } } pixel=Dc; switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case SrcAtopCompositeOp: { pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa)); break; } case BlendCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc); break; } case BlurCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } case DisplaceCompositeOp: case DistortCompositeOp: { pixel=Sc; break; } case BumpmapCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc; break; } case ChangeMaskCompositeOp: { pixel=Dc; break; } case ClearCompositeOp: { pixel=0.0; break; } case ColorBurnCompositeOp: { if ((Sca == 0.0) && (Dca == Da)) { pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa)); break; } if (Sca == 0.0) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-DcaDa)* SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorDodgeCompositeOp: { if ((Sca*Da+Dca*Sa) >= Sa*Da) pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); else pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &sans,&sans,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case CopyAlphaCompositeOp: { pixel=Dc; break; } case CopyBlackCompositeOp: { if (channel == BlackPixelChannel) pixel=(MagickRealType) (QuantumRange- GetPixelBlack(source_image,p)); break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { if (channel == BluePixelChannel) pixel=(MagickRealType) GetPixelBlue(source_image,p); break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { if (channel == GreenPixelChannel) pixel=(MagickRealType) GetPixelGreen(source_image,p); break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case DarkenCompositeOp: { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ if ((Sca*Da) < (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case DifferenceCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa)); break; } case DissolveCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa* canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc); break; } case DivideDstCompositeOp: { if ((fabs((double) Sca) < MagickEpsilon) && (fabs((double) Dca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (fabs((double) Dca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case DivideSrcCompositeOp: { if ((fabs((double) Dca) < MagickEpsilon) && (fabs((double) Sca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } if (fabs((double) Sca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } pixel=QuantumRange*gamma*(Dca*Sa*SaSca+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } case DstAtopCompositeOp: { pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da)); break; } case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Dca; break; } case DstInCompositeOp: { pixel=QuantumRange*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*(Dca*(1.0-Sa)); break; } case DstOverCompositeOp: { pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da)); break; } case ExclusionCompositeOp: { pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0- Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardMixCompositeOp: { pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange); break; } case HueCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&sans,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case InCompositeOp: case SrcInCompositeOp: { pixel=QuantumRange*(Sca*Da); break; } case LinearBurnCompositeOp: { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da); break; } case LinearDodgeCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc); break; } case LinearLightCompositeOp: { /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca); break; } case LightenCompositeOp: { if ((Sca*Da) > (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case LightenIntensityCompositeOp: { /* Lighten is equivalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case LuminizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&sans,&luma); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case MathematicsCompositeOp: { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+ geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+ geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case MinusDstCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa); break; } case MinusSrcCompositeOp: { /* Minus source from canvas. f(Sc,Dc) = Sc - Dc */ pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da); break; } case ModulateCompositeOp: { ssize_t offset; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint); if (offset == 0) { pixel=Dc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ModulusAddCompositeOp: { pixel=Sc+Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case ModulusSubtractCompositeOp: { pixel=Sc-Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case MultiplyCompositeOp: { pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case OutCompositeOp: case SrcOutCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)); break; } case OverCompositeOp: case SrcOverCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); break; } case OverlayCompositeOp: { if ((2.0*Dca) < Da) { pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0- Da)); break; } pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+ Sca*(1.0-Da)); break; } case PegtopLightCompositeOp: { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs((double) Da) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sca); break; } pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0- Da)+Dca*(1.0-Sa)); break; } case PinLightCompositeOp: { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if ((Dca*Sa) < (Da*(2.0*Sca-Sa))) { pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); break; } if ((Dca*Sa) > (2.0*Sca*Da)) { pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca); break; } case PlusCompositeOp: { pixel=QuantumRange*(Sca+Dca); break; } case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ScreenCompositeOp: { /* Screen: a negated multiply: f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca); break; } case SoftLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-DcaDa))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*DcaDa* (4.0*DcaDa+1.0)*(DcaDa-1.0)+7.0*DcaDa)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow(DcaDa,0.5)- DcaDa)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case StereoCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case ThresholdCompositeOp: { MagickRealType delta; delta=Sc-Dc; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) { pixel=gamma*Dc; break; } pixel=gamma*(Dc+delta*amount); break; } case VividLightCompositeOp: { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs((double) Sa) < MagickEpsilon) || (fabs((double) (Sca-Sa)) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if ((2.0*Sca) <= Sa) { pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)* PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(2.0* (Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case XorCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } default: { pixel=Sc; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); if (canvas_image != (Image * ) NULL) canvas_image=DestroyImage(canvas_image); else source_image=DestroyImage(source_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o texture_image: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture, ExceptionInfo *exception) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace,exception); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod, exception); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->alpha_trait != UndefinedPixelTrait) || (texture_image->alpha_trait != UndefinedPixelTrait))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,texture_image,image->compose, MagickTrue,x+texture_image->tile_offset.x,y+ texture_image->tile_offset.y,exception); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(texture_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const Quantum *p, *pixels; register ssize_t x; register Quantum *q; size_t width; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x, (y+texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { register ssize_t j; p=pixels; width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; for (j=0; j < (ssize_t) width; j++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++) { PixelChannel channel = GetPixelChannelChannel(texture_image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait texture_traits=GetPixelChannelTraits(texture_image, channel); if ((traits == UndefinedPixelTrait) || (texture_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); } } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_933_0
crossvul-cpp_data_bad_2711_0
/* * Copyright (c) 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Original code by Matt Thomas, Digital Equipment Corporation * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete IS-IS & CLNP support. */ /* \summary: ISO CLNS, ESIS, and ISIS printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "ether.h" #include "nlpid.h" #include "extract.h" #include "gmpls.h" #include "oui.h" #include "signature.h" static const char tstr[] = " [|isis]"; /* * IS-IS is defined in ISO 10589. Look there for protocol definitions. */ #define SYSTEM_ID_LEN ETHER_ADDR_LEN #define NODE_ID_LEN SYSTEM_ID_LEN+1 #define LSP_ID_LEN SYSTEM_ID_LEN+2 #define ISIS_VERSION 1 #define ESIS_VERSION 1 #define CLNP_VERSION 1 #define ISIS_PDU_TYPE_MASK 0x1F #define ESIS_PDU_TYPE_MASK 0x1F #define CLNP_PDU_TYPE_MASK 0x1F #define CLNP_FLAG_MASK 0xE0 #define ISIS_LAN_PRIORITY_MASK 0x7F #define ISIS_PDU_L1_LAN_IIH 15 #define ISIS_PDU_L2_LAN_IIH 16 #define ISIS_PDU_PTP_IIH 17 #define ISIS_PDU_L1_LSP 18 #define ISIS_PDU_L2_LSP 20 #define ISIS_PDU_L1_CSNP 24 #define ISIS_PDU_L2_CSNP 25 #define ISIS_PDU_L1_PSNP 26 #define ISIS_PDU_L2_PSNP 27 static const struct tok isis_pdu_values[] = { { ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"}, { ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"}, { ISIS_PDU_PTP_IIH, "p2p IIH"}, { ISIS_PDU_L1_LSP, "L1 LSP"}, { ISIS_PDU_L2_LSP, "L2 LSP"}, { ISIS_PDU_L1_CSNP, "L1 CSNP"}, { ISIS_PDU_L2_CSNP, "L2 CSNP"}, { ISIS_PDU_L1_PSNP, "L1 PSNP"}, { ISIS_PDU_L2_PSNP, "L2 PSNP"}, { 0, NULL} }; /* * A TLV is a tuple of a type, length and a value and is normally used for * encoding information in all sorts of places. This is an enumeration of * the well known types. * * list taken from rfc3359 plus some memory from veterans ;-) */ #define ISIS_TLV_AREA_ADDR 1 /* iso10589 */ #define ISIS_TLV_IS_REACH 2 /* iso10589 */ #define ISIS_TLV_ESNEIGH 3 /* iso10589 */ #define ISIS_TLV_PART_DIS 4 /* iso10589 */ #define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */ #define ISIS_TLV_ISNEIGH 6 /* iso10589 */ #define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */ #define ISIS_TLV_PADDING 8 /* iso10589 */ #define ISIS_TLV_LSP 9 /* iso10589 */ #define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */ #define ISIS_TLV_CHECKSUM 12 /* rfc3358 */ #define ISIS_TLV_CHECKSUM_MINLEN 2 #define ISIS_TLV_POI 13 /* rfc6232 */ #define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */ #define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2 #define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */ #define ISIS_TLV_DECNET_PHASE4 42 #define ISIS_TLV_LUCENT_PRIVATE 66 #define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */ #define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */ #define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */ #define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */ #define ISIS_TLV_IDRP_INFO_MINLEN 1 #define ISIS_TLV_IPADDR 132 /* rfc1195 */ #define ISIS_TLV_IPAUTH 133 /* rfc1195 */ #define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_HOSTNAME 137 /* rfc2763 */ #define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */ #define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */ #define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */ #define ISIS_TLV_NORTEL_PRIVATE1 176 #define ISIS_TLV_NORTEL_PRIVATE2 177 #define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */ #define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1 #define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2 #define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED_MINLEN 2 #define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */ #define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */ #define ISIS_TLV_IIH_SEQNR_MINLEN 4 #define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */ #define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3 static const struct tok isis_tlv_values[] = { { ISIS_TLV_AREA_ADDR, "Area address(es)"}, { ISIS_TLV_IS_REACH, "IS Reachability"}, { ISIS_TLV_ESNEIGH, "ES Neighbor(s)"}, { ISIS_TLV_PART_DIS, "Partition DIS"}, { ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"}, { ISIS_TLV_ISNEIGH, "IS Neighbor(s)"}, { ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"}, { ISIS_TLV_PADDING, "Padding"}, { ISIS_TLV_LSP, "LSP entries"}, { ISIS_TLV_AUTH, "Authentication"}, { ISIS_TLV_CHECKSUM, "Checksum"}, { ISIS_TLV_POI, "Purge Originator Identifier"}, { ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"}, { ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"}, { ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"}, { ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"}, { ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"}, { ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"}, { ISIS_TLV_PROTOCOLS, "Protocols supported"}, { ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"}, { ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"}, { ISIS_TLV_IPADDR, "IPv4 Interface address(es)"}, { ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"}, { ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"}, { ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"}, { ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"}, { ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"}, { ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"}, { ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"}, { ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"}, { ISIS_TLV_HOSTNAME, "Hostname"}, { ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"}, { ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"}, { ISIS_TLV_MT_SUPPORTED, "Multi Topology"}, { ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"}, { ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"}, { ISIS_TLV_IP6_REACH, "IPv6 reachability"}, { ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"}, { ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"}, { ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"}, { ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"}, { 0, NULL } }; #define ESIS_OPTION_PROTOCOLS 129 #define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */ #define ESIS_OPTION_SECURITY 197 /* iso9542 */ #define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */ #define ESIS_OPTION_PRIORITY 205 /* iso9542 */ #define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */ #define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */ static const struct tok esis_option_values[] = { { ESIS_OPTION_PROTOCOLS, "Protocols supported"}, { ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" }, { ESIS_OPTION_SECURITY, "Security" }, { ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" }, { ESIS_OPTION_PRIORITY, "Priority" }, { ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" }, { ESIS_OPTION_SNPA_MASK, "SNPA Mask" }, { 0, NULL } }; #define CLNP_OPTION_DISCARD_REASON 193 #define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */ #define CLNP_OPTION_SECURITY 197 /* iso8473 */ #define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */ #define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */ #define CLNP_OPTION_PADDING 204 /* iso8473 */ #define CLNP_OPTION_PRIORITY 205 /* iso8473 */ static const struct tok clnp_option_values[] = { { CLNP_OPTION_DISCARD_REASON, "Discard Reason"}, { CLNP_OPTION_PRIORITY, "Priority"}, { CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"}, { CLNP_OPTION_SECURITY, "Security"}, { CLNP_OPTION_SOURCE_ROUTING, "Source Routing"}, { CLNP_OPTION_ROUTE_RECORDING, "Route Recording"}, { CLNP_OPTION_PADDING, "Padding"}, { 0, NULL } }; static const struct tok clnp_option_rfd_class_values[] = { { 0x0, "General"}, { 0x8, "Address"}, { 0x9, "Source Routeing"}, { 0xa, "Lifetime"}, { 0xb, "PDU Discarded"}, { 0xc, "Reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_general_values[] = { { 0x0, "Reason not specified"}, { 0x1, "Protocol procedure error"}, { 0x2, "Incorrect checksum"}, { 0x3, "PDU discarded due to congestion"}, { 0x4, "Header syntax error (cannot be parsed)"}, { 0x5, "Segmentation needed but not permitted"}, { 0x6, "Incomplete PDU received"}, { 0x7, "Duplicate option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_address_values[] = { { 0x0, "Destination address unreachable"}, { 0x1, "Destination address unknown"}, { 0, NULL } }; static const struct tok clnp_option_rfd_source_routeing_values[] = { { 0x0, "Unspecified source routeing error"}, { 0x1, "Syntax error in source routeing field"}, { 0x2, "Unknown address in source routeing field"}, { 0x3, "Path not acceptable"}, { 0, NULL } }; static const struct tok clnp_option_rfd_lifetime_values[] = { { 0x0, "Lifetime expired while data unit in transit"}, { 0x1, "Lifetime expired during reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_pdu_discard_values[] = { { 0x0, "Unsupported option not specified"}, { 0x1, "Unsupported protocol version"}, { 0x2, "Unsupported security option"}, { 0x3, "Unsupported source routeing option"}, { 0x4, "Unsupported recording of route option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_reassembly_values[] = { { 0x0, "Reassembly interference"}, { 0, NULL } }; /* array of 16 error-classes */ static const struct tok *clnp_option_rfd_error_class[] = { clnp_option_rfd_general_values, NULL, NULL, NULL, NULL, NULL, NULL, NULL, clnp_option_rfd_address_values, clnp_option_rfd_source_routeing_values, clnp_option_rfd_lifetime_values, clnp_option_rfd_pdu_discard_values, clnp_option_rfd_reassembly_values, NULL, NULL, NULL }; #define CLNP_OPTION_OPTION_QOS_MASK 0x3f #define CLNP_OPTION_SCOPE_MASK 0xc0 #define CLNP_OPTION_SCOPE_SA_SPEC 0x40 #define CLNP_OPTION_SCOPE_DA_SPEC 0x80 #define CLNP_OPTION_SCOPE_GLOBAL 0xc0 static const struct tok clnp_option_scope_values[] = { { CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"}, { CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"}, { CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_values[] = { { 0x0, "partial"}, { 0x1, "complete"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_string_values[] = { { CLNP_OPTION_SOURCE_ROUTING, "source routing"}, { CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"}, { 0, NULL } }; static const struct tok clnp_option_qos_global_values[] = { { 0x20, "reserved"}, { 0x10, "sequencing vs. delay"}, { 0x08, "congested"}, { 0x04, "delay vs. cost"}, { 0x02, "error vs. delay"}, { 0x01, "error vs. cost"}, { 0, NULL } }; #define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */ #define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */ #define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */ static const struct tok isis_ext_is_reach_subtlv_values[] = { { ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" }, { ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" }, { ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" }, { ISIS_SUBTLV_SPB_METRIC, "SPB Metric" }, { 250, "Reserved for cisco specific extensions" }, { 251, "Reserved for cisco specific extensions" }, { 252, "Reserved for cisco specific extensions" }, { 253, "Reserved for cisco specific extensions" }, { 254, "Reserved for cisco specific extensions" }, { 255, "Reserved for future expansion" }, { 0, NULL } }; #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */ static const struct tok isis_ext_ip_reach_subtlv_values[] = { { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" }, { 0, NULL } }; static const struct tok isis_subtlv_link_attribute_values[] = { { 0x01, "Local Protection Available" }, { 0x02, "Link excluded from local protection path" }, { 0x04, "Local maintenance required"}, { 0, NULL } }; #define ISIS_SUBTLV_AUTH_SIMPLE 1 #define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */ #define ISIS_SUBTLV_AUTH_MD5 54 #define ISIS_SUBTLV_AUTH_MD5_LEN 16 #define ISIS_SUBTLV_AUTH_PRIVATE 255 static const struct tok isis_subtlv_auth_values[] = { { ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"}, { ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"}, { ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"}, { ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"}, { 0, NULL } }; #define ISIS_SUBTLV_IDRP_RES 0 #define ISIS_SUBTLV_IDRP_LOCAL 1 #define ISIS_SUBTLV_IDRP_ASN 2 static const struct tok isis_subtlv_idrp_values[] = { { ISIS_SUBTLV_IDRP_RES, "Reserved"}, { ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"}, { ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"}, { 0, NULL} }; #define ISIS_SUBTLV_SPB_MCID 4 #define ISIS_SUBTLV_SPB_DIGEST 5 #define ISIS_SUBTLV_SPB_BVID 6 #define ISIS_SUBTLV_SPB_INSTANCE 1 #define ISIS_SUBTLV_SPBM_SI 3 #define ISIS_SPB_MCID_LEN 51 #define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102 #define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33 #define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6 #define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19 #define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8 static const struct tok isis_mt_port_cap_subtlv_values[] = { { ISIS_SUBTLV_SPB_MCID, "SPB MCID" }, { ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" }, { ISIS_SUBTLV_SPB_BVID, "SPB BVID" }, { 0, NULL } }; static const struct tok isis_mt_capability_subtlv_values[] = { { ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" }, { ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" }, { 0, NULL } }; struct isis_spb_mcid { uint8_t format_id; uint8_t name[32]; uint8_t revision_lvl[2]; uint8_t digest[16]; }; struct isis_subtlv_spb_mcid { struct isis_spb_mcid mcid; struct isis_spb_mcid aux_mcid; }; struct isis_subtlv_spb_instance { uint8_t cist_root_id[8]; uint8_t cist_external_root_path_cost[4]; uint8_t bridge_priority[2]; uint8_t spsourceid[4]; uint8_t no_of_trees; }; #define CLNP_SEGMENT_PART 0x80 #define CLNP_MORE_SEGMENTS 0x40 #define CLNP_REQUEST_ER 0x20 static const struct tok clnp_flag_values[] = { { CLNP_SEGMENT_PART, "Segmentation permitted"}, { CLNP_MORE_SEGMENTS, "more Segments"}, { CLNP_REQUEST_ER, "request Error Report"}, { 0, NULL} }; #define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4) #define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3) #define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80) #define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78) #define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40) #define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20) #define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10) #define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8) #define ISIS_MASK_MTID(x) ((x)&0x0fff) #define ISIS_MASK_MTFLAGS(x) ((x)&0xf000) static const struct tok isis_mt_flag_values[] = { { 0x4000, "ATT bit set"}, { 0x8000, "Overload bit set"}, { 0, NULL} }; #define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80) #define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20) #define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40) #define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f) #define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1) static const struct tok isis_mt_values[] = { { 0, "IPv4 unicast"}, { 1, "In-Band Management"}, { 2, "IPv6 unicast"}, { 3, "Multicast"}, { 4095, "Development, Experimental or Proprietary"}, { 0, NULL } }; static const struct tok isis_iih_circuit_type_values[] = { { 1, "Level 1 only"}, { 2, "Level 2 only"}, { 3, "Level 1, Level 2"}, { 0, NULL} }; #define ISIS_LSP_TYPE_UNUSED0 0 #define ISIS_LSP_TYPE_LEVEL_1 1 #define ISIS_LSP_TYPE_UNUSED2 2 #define ISIS_LSP_TYPE_LEVEL_2 3 static const struct tok isis_lsp_istype_values[] = { { ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_1, "L1 IS"}, { ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_2, "L2 IS"}, { 0, NULL } }; /* * Katz's point to point adjacency TLV uses codes to tell us the state of * the remote adjacency. Enumerate them. */ #define ISIS_PTP_ADJ_UP 0 #define ISIS_PTP_ADJ_INIT 1 #define ISIS_PTP_ADJ_DOWN 2 static const struct tok isis_ptp_adjancey_values[] = { { ISIS_PTP_ADJ_UP, "Up" }, { ISIS_PTP_ADJ_INIT, "Initializing" }, { ISIS_PTP_ADJ_DOWN, "Down" }, { 0, NULL} }; struct isis_tlv_ptp_adj { uint8_t adjacency_state; uint8_t extd_local_circuit_id[4]; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; uint8_t neighbor_extd_local_circuit_id[4]; }; static void osi_print_cksum(netdissect_options *, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length); static int clnp_print(netdissect_options *, const uint8_t *, u_int); static void esis_print(netdissect_options *, const uint8_t *, u_int); static int isis_print(netdissect_options *, const uint8_t *, u_int); struct isis_metric_block { uint8_t metric_default; uint8_t metric_delay; uint8_t metric_expense; uint8_t metric_error; }; struct isis_tlv_is_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_nodeid[NODE_ID_LEN]; }; struct isis_tlv_es_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; }; struct isis_tlv_ip_reach { struct isis_metric_block isis_metric_block; uint8_t prefix[4]; uint8_t mask[4]; }; static const struct tok isis_is_reach_virtual_values[] = { { 0, "IsNotVirtual"}, { 1, "IsVirtual"}, { 0, NULL } }; static const struct tok isis_restart_flag_values[] = { { 0x1, "Restart Request"}, { 0x2, "Restart Acknowledgement"}, { 0x4, "Suppress adjacency advertisement"}, { 0, NULL } }; struct isis_common_header { uint8_t nlpid; uint8_t fixed_len; uint8_t version; /* Protocol version */ uint8_t id_length; uint8_t pdu_type; /* 3 MSbits are reserved */ uint8_t pdu_version; /* Packet format version */ uint8_t reserved; uint8_t max_area; }; struct isis_iih_lan_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t priority; uint8_t lan_id[NODE_ID_LEN]; }; struct isis_iih_ptp_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t circuit_id; }; struct isis_lsp_header { uint8_t pdu_len[2]; uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; uint8_t typeblock; }; struct isis_csnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; uint8_t start_lsp_id[LSP_ID_LEN]; uint8_t end_lsp_id[LSP_ID_LEN]; }; struct isis_psnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; }; struct isis_tlv_lsp { uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; }; #define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header)) #define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header)) #define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header)) #define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header)) #define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header)) #define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header)) void isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length) { if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */ ND_PRINT((ndo, "|OSI")); return; } if (ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p)); switch (*p) { case NLPID_CLNP: if (!clnp_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_ESIS: esis_print(ndo, p, length); return; case NLPID_ISIS: if (!isis_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_NULLNS: ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); break; case NLPID_Q933: q933_print(ndo, p + 1, length - 1); break; case NLPID_IP: ip_print(ndo, p + 1, length - 1); break; case NLPID_IP6: ip6_print(ndo, p + 1, length - 1); break; case NLPID_PPP: ppp_print(ndo, p + 1, length - 1); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p)); ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); if (length > 1) print_unknown_data(ndo, p, "\n\t", length); break; } } #define CLNP_PDU_ER 1 #define CLNP_PDU_DT 28 #define CLNP_PDU_MD 29 #define CLNP_PDU_ERQ 30 #define CLNP_PDU_ERP 31 static const struct tok clnp_pdu_values[] = { { CLNP_PDU_ER, "Error Report"}, { CLNP_PDU_MD, "MD"}, { CLNP_PDU_DT, "Data"}, { CLNP_PDU_ERQ, "Echo Request"}, { CLNP_PDU_ERP, "Echo Response"}, { 0, NULL } }; struct clnp_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t lifetime; /* units of 500ms */ uint8_t type; uint8_t segment_length[2]; uint8_t cksum[2]; }; struct clnp_segment_header_t { uint8_t data_unit_id[2]; uint8_t segment_offset[2]; uint8_t total_length[2]; }; /* * clnp_print * Decode CLNP packets. Return 0 on error. */ static int clnp_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr,*source_address,*dest_address; u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags; const struct clnp_header_t *clnp_header; const struct clnp_segment_header_t *clnp_segment_header; uint8_t rfd_error_major,rfd_error_minor; clnp_header = (const struct clnp_header_t *) pptr; ND_TCHECK(*clnp_header); li = clnp_header->length_indicator; optr = pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "CLNP")); /* * Sanity checking of the header. */ if (clnp_header->version != CLNP_VERSION) { ND_PRINT((ndo, "version %d packet not supported", clnp_header->version)); return (0); } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return (0); } if (li < sizeof(struct clnp_header_t)) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return (0); } /* FIXME further header sanity checking */ clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK; clnp_flags = clnp_header->type & CLNP_FLAG_MASK; pptr += sizeof(struct clnp_header_t); li -= sizeof(struct clnp_header_t); if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); dest_address_length = *pptr; pptr += 1; li -= 1; if (li < dest_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, dest_address_length); dest_address = pptr; pptr += dest_address_length; li -= dest_address_length; if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); source_address_length = *pptr; pptr += 1; li -= 1; if (li < source_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, source_address_length); source_address = pptr; pptr += source_address_length; li -= source_address_length; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s > %s, %s, length %u", ndo->ndo_eflag ? "" : ", ", isonsap_string(ndo, source_address, source_address_length), isonsap_string(ndo, dest_address, dest_address_length), tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type), length)); return (1); } ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x", tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type), clnp_header->length_indicator, clnp_header->version, clnp_header->lifetime/2, (clnp_header->lifetime%2)*5, EXTRACT_16BITS(clnp_header->segment_length), EXTRACT_16BITS(clnp_header->cksum))); osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7, clnp_header->length_indicator); ND_PRINT((ndo, "\n\tFlags [%s]", bittok2str(clnp_flag_values, "none", clnp_flags))); ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length), dest_address_length, isonsap_string(ndo, dest_address, dest_address_length))); if (clnp_flags & CLNP_SEGMENT_PART) { if (li < sizeof(const struct clnp_segment_header_t)) { ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part")); return (0); } clnp_segment_header = (const struct clnp_segment_header_t *) pptr; ND_TCHECK(*clnp_segment_header); ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u", EXTRACT_16BITS(clnp_segment_header->data_unit_id), EXTRACT_16BITS(clnp_segment_header->segment_offset), EXTRACT_16BITS(clnp_segment_header->total_length))); pptr+=sizeof(const struct clnp_segment_header_t); li-=sizeof(const struct clnp_segment_header_t); } /* now walk the options */ while (li >= 2) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return (0); } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return (0); } ND_TCHECK2(*pptr, opli); li -= opli; tptr = pptr; tlen = opli; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(clnp_option_values,"Unknown",op), op, opli)); /* * We've already checked that the entire option is present * in the captured packet with the ND_TCHECK2() call. * Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2() * checks. * We do, however, need to check tlen, to make sure we * don't run past the end of the option. */ switch (op) { case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */ case CLNP_OPTION_SOURCE_ROUTING: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "%s %s", tok2str(clnp_option_sr_rr_values,"Unknown",*tptr), tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op))); nsap_offset=*(tptr+1); if (nsap_offset == 0) { ND_PRINT((ndo, " Bad NSAP offset (0)")); break; } nsap_offset-=1; /* offset to nsap list */ if (nsap_offset > tlen) { ND_PRINT((ndo, " Bad NSAP offset (past end of option)")); break; } tptr+=nsap_offset; tlen-=nsap_offset; while (tlen > 0) { source_address_length=*tptr; if (tlen < source_address_length+1) { ND_PRINT((ndo, "\n\t NSAP address goes past end of option")); break; } if (source_address_length > 0) { source_address=(tptr+1); ND_TCHECK2(*source_address, source_address_length); ND_PRINT((ndo, "\n\t NSAP address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length))); } tlen-=source_address_length+1; } break; case CLNP_OPTION_PRIORITY: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "0x%1x", *tptr&0x0f)); break; case CLNP_OPTION_QOS_MAINTENANCE: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s", tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK))); if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL) ND_PRINT((ndo, "\n\t QoS Flags [%s]", bittok2str(clnp_option_qos_global_values, "none", *tptr&CLNP_OPTION_OPTION_QOS_MASK))); break; case CLNP_OPTION_SECURITY: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u", tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK), *(tptr+1))); break; case CLNP_OPTION_DISCARD_REASON: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } rfd_error_major = (*tptr&0xf0) >> 4; rfd_error_minor = *tptr&0x0f; ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)", tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major), rfd_error_major, tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor), rfd_error_minor)); break; case CLNP_OPTION_PADDING: ND_PRINT((ndo, "padding data")); break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } switch (clnp_pdu_type) { case CLNP_PDU_ER: /* fall through */ case CLNP_PDU_ERP: ND_TCHECK(*pptr); if (*(pptr) == NLPID_CLNP) { ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); /* FIXME recursion protection */ clnp_print(ndo, pptr, length - clnp_header->length_indicator); break; } case CLNP_PDU_DT: case CLNP_PDU_MD: case CLNP_PDU_ERQ: default: /* dump the PDU specific data */ if (length-(pptr-optr) > 0) { ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator)); print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr)); } } return (1); trunc: ND_PRINT((ndo, "[|clnp]")); return (1); } #define ESIS_PDU_REDIRECT 6 #define ESIS_PDU_ESH 2 #define ESIS_PDU_ISH 4 static const struct tok esis_pdu_values[] = { { ESIS_PDU_REDIRECT, "redirect"}, { ESIS_PDU_ESH, "ESH"}, { ESIS_PDU_ISH, "ISH"}, { 0, NULL } }; struct esis_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t reserved; uint8_t type; uint8_t holdtime[2]; uint8_t cksum[2]; }; static void esis_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr; u_int li,esis_pdu_type,source_address_length, source_address_number; const struct esis_header_t *esis_header; if (!ndo->ndo_eflag) ND_PRINT((ndo, "ES-IS")); if (length <= 2) { ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!")); return; } esis_header = (const struct esis_header_t *) pptr; ND_TCHECK(*esis_header); li = esis_header->length_indicator; optr = pptr; /* * Sanity checking of the header. */ if (esis_header->nlpid != NLPID_ESIS) { ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid)); return; } if (esis_header->version != ESIS_VERSION) { ND_PRINT((ndo, " version %d packet not supported", esis_header->version)); return; } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return; } if (li < sizeof(struct esis_header_t) + 2) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return; } esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s, length %u", ndo->ndo_eflag ? "" : ", ", tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type), length)); return; } else ND_PRINT((ndo, "%slength %u\n\t%s (%u)", ndo->ndo_eflag ? "" : ", ", length, tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type), esis_pdu_type)); ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" )); ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum))); osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li); ND_PRINT((ndo, ", holding time: %us, length indicator: %u", EXTRACT_16BITS(esis_header->holdtime), li)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t)); pptr += sizeof(struct esis_header_t); li -= sizeof(struct esis_header_t); switch (esis_pdu_type) { case ESIS_PDU_REDIRECT: { const uint8_t *dst, *snpa, *neta; u_int dstl, snpal, netal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } dstl = *pptr; pptr++; li--; ND_TCHECK2(*pptr, dstl); if (li < dstl) { ND_PRINT((ndo, ", bad redirect/li")); return; } dst = pptr; pptr += dstl; li -= dstl; ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl))); ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpal = *pptr; pptr++; li--; ND_TCHECK2(*pptr, snpal); if (li < snpal) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpa = pptr; pptr += snpal; li -= snpal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } netal = *pptr; pptr++; ND_TCHECK2(*pptr, netal); if (li < netal) { ND_PRINT((ndo, ", bad redirect/li")); return; } neta = pptr; pptr += netal; li -= netal; if (snpal == 6) ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, etheraddr_string(ndo, snpa))); else ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal))); if (netal != 0) ND_PRINT((ndo, "\n\t NET (length: %u) %s", netal, isonsap_string(ndo, neta, netal))); break; } case ESIS_PDU_ESH: ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_number = *pptr; pptr++; li--; ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number)); while (source_address_number > 0) { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad esh/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; source_address_number--; } break; case ESIS_PDU_ISH: { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad ish/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad ish/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; break; } default: if (ndo->ndo_vflag <= 1) { if (pptr < ndo->ndo_snapend) print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr); } return; } /* now walk the options */ while (li != 0) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return; } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return; } li -= opli; tptr = pptr; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(esis_option_values,"Unknown",op), op, opli)); switch (op) { case ESIS_OPTION_ES_CONF_TIME: if (opli == 2) { ND_TCHECK2(*pptr, 2); ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr))); } else ND_PRINT((ndo, "(bad length)")); break; case ESIS_OPTION_PROTOCOLS: while (opli>0) { ND_TCHECK(*pptr); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (opli>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; opli--; } break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ case ESIS_OPTION_QOS_MAINTENANCE: case ESIS_OPTION_SECURITY: case ESIS_OPTION_PRIORITY: case ESIS_OPTION_ADDRESS_MASK: case ESIS_OPTION_SNPA_MASK: default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } trunc: return; } static void isis_print_mcid(netdissect_options *ndo, const struct isis_spb_mcid *mcid) { int i; ND_TCHECK(*mcid); ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id)); if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend)) goto trunc; ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl))); ND_PRINT((ndo, ", Digest: ")); for(i=0;i<16;i++) ND_PRINT((ndo, "%.2x ", mcid->digest[i])); trunc: ND_PRINT((ndo, "%s", tstr)); } static int isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN) goto trunc; subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN; len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; break; } case ISIS_SUBTLV_SPB_DIGEST: { if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN) goto trunc; ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static int isis_print_mt_capability_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len, tmp; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); len = len - 2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_INSTANCE: if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN) goto trunc; ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr))); tptr = tptr + 2; ND_PRINT((ndo, "\n\t RES: %d", EXTRACT_16BITS(tptr) >> 5)); ND_PRINT((ndo, ", V: %d", (EXTRACT_16BITS(tptr) >> 4) & 0x0001)); ND_PRINT((ndo, ", SPSource-ID: %d", (EXTRACT_32BITS(tptr) & 0x000fffff))); tptr = tptr+4; ND_PRINT((ndo, ", No of Trees: %x", *(tptr))); tmp = *(tptr++); len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; while (tmp) { if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN) goto trunc; ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d", *(tptr) >> 7, (*(tptr) >> 6) & 0x01, (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f))); tptr++; ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr + 4; ND_PRINT((ndo, ", BVID: %d, SPVID: %d", (EXTRACT_24BITS(tptr) >> 12) & 0x000fff, EXTRACT_24BITS(tptr) & 0x000fff)); tptr = tptr + 3; len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; tmp--; } break; case ISIS_SUBTLV_SPBM_SI: if (stlv_len < 8) goto trunc; ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr))); tptr = tptr+2; ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12, (EXTRACT_16BITS(tptr)) & 0x0fff)); tptr = tptr+2; len = len - 8; stlv_len = stlv_len - 8; while (stlv_len >= 4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d", (EXTRACT_32BITS(tptr) >> 31), (EXTRACT_32BITS(tptr) >> 30) & 0x01, (EXTRACT_32BITS(tptr) >> 24) & 0x03f, (EXTRACT_32BITS(tptr)) & 0x0ffffff)); tptr = tptr + 4; len = len - 4; stlv_len = stlv_len - 4; } break; default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } /* shared routine for printing system, node and lsp-ids */ static char * isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } /* print the 4-byte metric block which is common found in the old-style TLVs */ static int isis_print_metric_block(netdissect_options *ndo, const struct isis_metric_block *isis_metric_block) { ND_PRINT((ndo, ", Default Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay)) ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense)) ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error)) ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal")); return(1); /* everything is ok */ } static int isis_print_tlv_ip_reach(netdissect_options *ndo, const uint8_t *cp, const char *ident, int length) { int prefix_len; const struct isis_tlv_ip_reach *tlv_ip_reach; tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp; while (length > 0) { if ((size_t)length < sizeof(*tlv_ip_reach)) { ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)", length, (unsigned long)sizeof(*tlv_ip_reach))); return (0); } if (!ND_TTEST(*tlv_ip_reach)) return (0); prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask)); if (prefix_len == -1) ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), ipaddr_string(ndo, (tlv_ip_reach->mask)))); else ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), prefix_len)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s", ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up", ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay)) ND_PRINT((ndo, "%s Delay Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense)) ND_PRINT((ndo, "%s Expense Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error)) ND_PRINT((ndo, "%s Error Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal")); length -= sizeof(struct isis_tlv_ip_reach); tlv_ip_reach++; } return (1); } /* * this is the common IP-REACH subTLV decoder it is called * from various EXTD-IP REACH TLVs (135,235,236,237) */ static int isis_print_ip_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, int subt, int subl, const char *ident) { /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr,subl); switch(subt) { case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */ case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32: while (subl >= 4) { ND_PRINT((ndo, ", 0x%08x (=%u)", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr))); tptr+=4; subl-=4; } break; case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64: while (subl >= 8) { ND_PRINT((ndo, ", 0x%08x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr+4))); tptr+=8; subl-=8; } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: ND_PRINT((ndo, "%s", ident)); ND_PRINT((ndo, "%s", tstr)); return(0); } /* * this is the common IS-REACH subTLV decoder it is called * from isis_print_ext_is_reach() */ static int isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } /* * this is the common IS-REACH decoder it is called * from various EXTD-IS REACH style TLVs (22,24,222) */ static int isis_print_ext_is_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, int tlv_type) { char ident_buffer[20]; int subtlv_type,subtlv_len,subtlv_sum_len; int proc_bytes = 0; /* how many bytes did we process ? */ if (!ND_TTEST2(*tptr, NODE_ID_LEN)) return(0); ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */ if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */ return(0); ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr))); tptr+=3; } if (!ND_TTEST2(*tptr, 1)) return(0); subtlv_sum_len=*(tptr++); /* read out subTLV length */ proc_bytes=NODE_ID_LEN+3+1; ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no ")); if (subtlv_sum_len) { ND_PRINT((ndo, " (%u)", subtlv_sum_len)); while (subtlv_sum_len>0) { if (!ND_TTEST2(*tptr,2)) return(0); subtlv_type=*(tptr++); subtlv_len=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer)) return(0); tptr+=subtlv_len; subtlv_sum_len-=(subtlv_len+2); proc_bytes+=(subtlv_len+2); } } return(proc_bytes); } /* * this is the common Multi Topology ID decoder * it is called from various MT-TLVs (222,229,235,237) */ static int isis_print_mtid(netdissect_options *ndo, const uint8_t *tptr, const char *ident) { if (!ND_TTEST2(*tptr, 2)) return(0); ND_PRINT((ndo, "%s%s", ident, tok2str(isis_mt_values, "Reserved for IETF Consensus", ISIS_MASK_MTID(EXTRACT_16BITS(tptr))))); ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]", ISIS_MASK_MTID(EXTRACT_16BITS(tptr)), bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr))))); return(2); } /* * this is the common extended IP reach decoder * it is called from TLVs (135,235,236,237) * we process the TLV and optional subTLVs and return * the amount of processed bytes */ static int isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } /* * Clear checksum and lifetime prior to signature verification. */ static void isis_clear_checksum_lifetime(void *header) { struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header; header_lsp->checksum[0] = 0; header_lsp->checksum[1] = 0; header_lsp->remaining_lifetime[0] = 0; header_lsp->remaining_lifetime[1] = 0; } /* * isis_print * Decode IS-IS packets. Return 0 on error. */ static int isis_print(netdissect_options *ndo, const uint8_t *p, u_int length) { const struct isis_common_header *isis_header; const struct isis_iih_lan_header *header_iih_lan; const struct isis_iih_ptp_header *header_iih_ptp; const struct isis_lsp_header *header_lsp; const struct isis_csnp_header *header_csnp; const struct isis_psnp_header *header_psnp; const struct isis_tlv_lsp *tlv_lsp; const struct isis_tlv_ptp_adj *tlv_ptp_adj; const struct isis_tlv_is_reach *tlv_is_reach; const struct isis_tlv_es_reach *tlv_es_reach; uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len; uint8_t ext_is_len, ext_ip_len, mt_len; const uint8_t *optr, *pptr, *tptr; u_short packet_len,pdu_len, key_id; u_int i,vendor_id; int sigcheck; packet_len=length; optr = p; /* initialize the _o_riginal pointer to the packet start - need it for parsing the checksum TLV and authentication TLV verification */ isis_header = (const struct isis_common_header *)p; ND_TCHECK(*isis_header); if (length < ISIS_COMMON_HEADER_SIZE) goto trunc; pptr = p+(ISIS_COMMON_HEADER_SIZE); header_iih_lan = (const struct isis_iih_lan_header *)pptr; header_iih_ptp = (const struct isis_iih_ptp_header *)pptr; header_lsp = (const struct isis_lsp_header *)pptr; header_csnp = (const struct isis_csnp_header *)pptr; header_psnp = (const struct isis_psnp_header *)pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "IS-IS")); /* * Sanity checking of the header. */ if (isis_header->version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->version)); return (0); } if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) { ND_PRINT((ndo, "system ID length of %d is not supported", isis_header->id_length)); return (0); } if (isis_header->pdu_version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version)); return (0); } if (length < isis_header->fixed_len) { ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length)); return (0); } if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) { ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE)); return (0); } max_area = isis_header->max_area; switch(max_area) { case 0: max_area = 3; /* silly shit */ break; case 255: ND_PRINT((ndo, "bad packet -- 255 areas")); return (0); default: break; } id_length = isis_header->id_length; switch(id_length) { case 0: id_length = 6; /* silly shit again */ break; case 1: /* 1-8 are valid sys-ID lenghts */ case 2: case 3: case 4: case 5: case 6: case 7: case 8: break; case 255: id_length = 0; /* entirely useless */ break; default: break; } /* toss any non 6-byte sys-ID len PDUs */ if (id_length != 6 ) { ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length)); return (0); } pdu_type=isis_header->pdu_type; /* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/ if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, "%s%s", ndo->ndo_eflag ? "" : ", ", tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type))); } else { /* ok they seem to want to know everything - lets fully decode it */ ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)", tok2str(isis_pdu_values, "unknown, type %u", pdu_type), isis_header->fixed_len, isis_header->version, isis_header->pdu_version, id_length, isis_header->id_length, max_area, isis_header->max_area)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */ return (0); /* for optionally debugging the common header */ } } switch (pdu_type) { case ISIS_PDU_L1_LAN_IIH: case ISIS_PDU_L2_LAN_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_lan); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", lan-id %s, prio %u", isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN), header_iih_lan->priority)); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_lan->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_lan->circuit_type))); ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u", isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN), (header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); break; case ISIS_PDU_PTP_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_ptp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_ptp->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_ptp->circuit_type))); ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u", header_iih_ptp->circuit_id, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); break; case ISIS_PDU_L1_LSP: case ISIS_PDU_L2_LSP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE)); return (0); } ND_TCHECK(*header_lsp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_lsp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime), EXTRACT_16BITS(header_lsp->checksum))); osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id, EXTRACT_16BITS(header_lsp->checksum), 12, length-12); ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s", pdu_len, ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : "")); if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) { ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : "")); ND_PRINT((ndo, "ATT bit set, ")); } ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : "")); ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)", ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock)))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); break; case ISIS_PDU_L1_CSNP: case ISIS_PDU_L2_CSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_csnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_csnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_csnp->source_id, NODE_ID_LEN), pdu_len)); ND_PRINT((ndo, "\n\t start lsp-id: %s", isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN))); ND_PRINT((ndo, "\n\t end lsp-id: %s", isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); break; case ISIS_PDU_L1_PSNP: case ISIS_PDU_L2_PSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) { ND_PRINT((ndo, "- bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_psnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_psnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_psnp->source_id, NODE_ID_LEN), pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); break; default: if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", length %u", length)); return (1); } (void)print_unknown_data(ndo, pptr, "\n\t ", length); return (0); } /* * Now print the TLV's. */ while (packet_len > 0) { ND_TCHECK2(*pptr, 2); if (packet_len < 2) goto trunc; tlv_type = *pptr++; tlv_len = *pptr++; tmp =tlv_len; /* copy temporary len & pointer to packet data */ tptr = pptr; packet_len -= 2; /* first lets see if we know the TLVs name*/ ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u", tok2str(isis_tlv_values, "unknown", tlv_type), tlv_type, tlv_len)); if (tlv_len == 0) /* something is invalid */ continue; if (packet_len < tlv_len) goto trunc; /* now check if we have a decoder otherwise do a hexdump at the end*/ switch (tlv_type) { case ISIS_TLV_AREA_ADDR: ND_TCHECK2(*tptr, 1); alen = *tptr++; while (tmp && alen < tmp) { ND_TCHECK2(*tptr, alen); ND_PRINT((ndo, "\n\t Area address (length: %u): %s", alen, isonsap_string(ndo, tptr, alen))); tptr += alen; tmp -= alen + 1; if (tmp==0) /* if this is the last area address do not attemt a boundary check */ break; ND_TCHECK2(*tptr, 1); alen = *tptr++; } break; case ISIS_TLV_ISNEIGH: while (tmp >= ETHER_ADDR_LEN) { ND_TCHECK2(*tptr, ETHER_ADDR_LEN); ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN))); tmp -= ETHER_ADDR_LEN; tptr += ETHER_ADDR_LEN; } break; case ISIS_TLV_ISNEIGH_VARLEN: if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */ goto trunctlv; lan_alen = *tptr++; /* LAN address length */ if (lan_alen == 0) { ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)")); break; } tmp --; ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen)); while (tmp >= lan_alen) { ND_TCHECK2(*tptr, lan_alen); ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen))); tmp -= lan_alen; tptr +=lan_alen; } break; case ISIS_TLV_PADDING: break; case ISIS_TLV_MT_IS_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; while (tmp >= 2+NODE_ID_LEN+3+1) { ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_ALIAS_ID: while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_EXT_IS_REACH: while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_REACH: ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */ ND_PRINT((ndo, "\n\t %s", tok2str(isis_is_reach_virtual_values, "bogus virtual flag 0x%02x", *tptr++))); tlv_is_reach = (const struct isis_tlv_is_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_is_reach)) { ND_TCHECK(*tlv_is_reach); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN))); isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_is_reach); tlv_is_reach++; } break; case ISIS_TLV_ESNEIGH: tlv_es_reach = (const struct isis_tlv_es_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_es_reach)) { ND_TCHECK(*tlv_es_reach); ND_PRINT((ndo, "\n\t ES Neighbor: %s", isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN))); isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_es_reach); tlv_es_reach++; } break; /* those two TLVs share the same format */ case ISIS_TLV_INT_IP_REACH: case ISIS_TLV_EXT_IP_REACH: if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len)) return (1); break; case ISIS_TLV_EXTD_IP_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP6_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6ADDR: while (tmp>=sizeof(struct in6_addr)) { ND_TCHECK2(*tptr, sizeof(struct in6_addr)); ND_PRINT((ndo, "\n\t IPv6 interface address: %s", ip6addr_string(ndo, tptr))); tptr += sizeof(struct in6_addr); tmp -= sizeof(struct in6_addr); } break; case ISIS_TLV_AUTH: ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t %s: ", tok2str(isis_subtlv_auth_values, "unknown Authentication type 0x%02x", *tptr))); switch (*tptr) { case ISIS_SUBTLV_AUTH_SIMPLE: if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_SUBTLV_AUTH_MD5: for(i=1;i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1) ND_PRINT((ndo, ", (invalid subTLV) ")); sigcheck = signature_verify(ndo, optr, length, tptr + 1, isis_clear_checksum_lifetime, header_lsp); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); break; case ISIS_SUBTLV_AUTH_GENERIC: ND_TCHECK2(*(tptr + 1), 2); key_id = EXTRACT_16BITS((tptr+1)); ND_PRINT((ndo, "%u, password: ", key_id)); for(i=1 + sizeof(uint16_t);i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } break; case ISIS_SUBTLV_AUTH_PRIVATE: default: if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_PTP_ADJ: tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr; if(tmp>=1) { ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)", tok2str(isis_ptp_adjancey_values, "unknown", *tptr), *tptr)); tmp--; } if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id); ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id))); tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id); } if(tmp>=SYSTEM_ID_LEN) { ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t Neighbor System-ID: %s", isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN))); tmp-=SYSTEM_ID_LEN; } if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id); ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id))); } break; case ISIS_TLV_PROTOCOLS: ND_PRINT((ndo, "\n\t NLPID(s): ")); while (tmp>0) { ND_TCHECK2(*(tptr), 1); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (tmp>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; tmp--; } break; case ISIS_TLV_MT_PORT_CAP: { ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d", (EXTRACT_16BITS (tptr) >> 12), (EXTRACT_16BITS (tptr) & 0x0fff))); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_port_cap_subtlv(ndo, tptr, tmp); break; } case ISIS_TLV_MT_CAPABILITY: ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d", (EXTRACT_16BITS(tptr) >> 15) & 0x01, (EXTRACT_16BITS(tptr) >> 12) & 0x07, EXTRACT_16BITS(tptr) & 0x0fff)); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_capability_subtlv(ndo, tptr, tmp); break; case ISIS_TLV_TE_ROUTER_ID: ND_TCHECK2(*pptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr))); break; case ISIS_TLV_IPADDR: while (tmp>=sizeof(struct in_addr)) { ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr += sizeof(struct in_addr); tmp -= sizeof(struct in_addr); } break; case ISIS_TLV_HOSTNAME: ND_PRINT((ndo, "\n\t Hostname: ")); if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_TLV_SHARED_RISK_GROUP: if (tmp < NODE_ID_LEN) break; ND_TCHECK2(*tptr, NODE_ID_LEN); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); tmp-=(NODE_ID_LEN); if (tmp < 1) break; ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered")); tmp--; if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); while (tmp>=4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr))); tptr+=4; tmp-=4; } break; case ISIS_TLV_LSP: tlv_lsp = (const struct isis_tlv_lsp *)tptr; while(tmp>=sizeof(struct isis_tlv_lsp)) { ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]); ND_PRINT((ndo, "\n\t lsp-id: %s", isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN))); ND_TCHECK2(tlv_lsp->sequence_number, 4); ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number))); ND_TCHECK2(tlv_lsp->remaining_lifetime, 2); ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime))); ND_TCHECK2(tlv_lsp->checksum, 2); ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum))); tmp-=sizeof(struct isis_tlv_lsp); tlv_lsp++; } break; case ISIS_TLV_CHECKSUM: if (tmp < ISIS_TLV_CHECKSUM_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN); ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr))); /* do not attempt to verify the checksum if it is zero * most likely a HMAC-MD5 TLV is also present and * to avoid conflicts the checksum TLV is zeroed. * see rfc3358 for details */ osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr, length); break; case ISIS_TLV_POI: if (tlv_len >= SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s", isis_print_id(tptr + 1, SYSTEM_ID_LEN))); } if (tlv_len == 2 * SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Received from System-ID: %s", isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN))); } break; case ISIS_TLV_MT_SUPPORTED: if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN) break; while (tmp>1) { /* length can only be a multiple of 2, otherwise there is something broken -> so decode down until length is 1 */ if (tmp!=1) { mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; } else { ND_PRINT((ndo, "\n\t invalid MT-ID")); break; } } break; case ISIS_TLV_RESTART_SIGNALING: /* first attempt to decode the flags */ if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN); ND_PRINT((ndo, "\n\t Flags [%s]", bittok2str(isis_restart_flag_values, "none", *tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; /* is there anything other than the flags field? */ if (tmp == 0) break; if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN); ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; /* is there an additional sysid field present ?*/ if (tmp == SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN))); } break; case ISIS_TLV_IDRP_INFO: if (tmp < ISIS_TLV_IDRP_INFO_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN); ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s", tok2str(isis_subtlv_idrp_values, "Unknown (0x%02x)", *tptr))); switch (*tptr++) { case ISIS_SUBTLV_IDRP_ASN: ND_TCHECK2(*tptr, 2); /* fetch AS number */ ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr))); break; case ISIS_SUBTLV_IDRP_LOCAL: case ISIS_SUBTLV_IDRP_RES: default: if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_LSP_BUFFERSIZE: if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN); ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr))); break; case ISIS_TLV_PART_DIS: while (tmp >= SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN))); tptr+=SYSTEM_ID_LEN; tmp-=SYSTEM_ID_LEN; } break; case ISIS_TLV_PREFIX_NEIGH: if (tmp < sizeof(struct isis_metric_block)) break; ND_TCHECK2(*tptr, sizeof(struct isis_metric_block)); ND_PRINT((ndo, "\n\t Metric Block")); isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr); tptr+=sizeof(struct isis_metric_block); tmp-=sizeof(struct isis_metric_block); while(tmp>0) { ND_TCHECK2(*tptr, 1); prefix_len=*tptr++; /* read out prefix length in semioctets*/ if (prefix_len < 2) { ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len)); break; } tmp--; if (tmp < prefix_len/2) break; ND_TCHECK2(*tptr, prefix_len / 2); ND_PRINT((ndo, "\n\t\tAddress: %s/%u", isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4)); tptr+=prefix_len/2; tmp-=prefix_len/2; } break; case ISIS_TLV_IIH_SEQNR: if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */ ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr))); break; case ISIS_TLV_VENDOR_PRIVATE: if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */ vendor_id = EXTRACT_24BITS(tptr); ND_PRINT((ndo, "\n\t Vendor: %s (%u)", tok2str(oui_values, "Unknown", vendor_id), vendor_id)); tptr+=3; tmp-=3; if (tmp > 0) /* hexdump the rest */ if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp)) return(0); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case ISIS_TLV_DECNET_PHASE4: case ISIS_TLV_LUCENT_PRIVATE: case ISIS_TLV_IPAUTH: case ISIS_TLV_NORTEL_PRIVATE1: case ISIS_TLV_NORTEL_PRIVATE2: default: if (ndo->ndo_vflag <= 1) { if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len)) return(0); } break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len)) return(0); } pptr += tlv_len; packet_len -= tlv_len; } if (packet_len != 0) { ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len)); } return (1); trunc: ND_PRINT((ndo, "%s", tstr)); return (1); trunctlv: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static void osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length) { uint16_t calculated_checksum; /* do not attempt to verify the checksum if it is zero, * if the offset is nonsense, * or the base pointer is not sane */ if (!checksum || checksum_offset < 0 || !ND_TTEST2(*(pptr + checksum_offset), 2) || (u_int)checksum_offset > length || !ND_TTEST2(*pptr, length)) { ND_PRINT((ndo, " (unverified)")); } else { #if 0 printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length); #endif calculated_checksum = create_osi_cksum(pptr, checksum_offset, length); if (checksum == calculated_checksum) { ND_PRINT((ndo, " (correct)")); } else { ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum)); } } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2711_0
crossvul-cpp_data_good_353_0
/* * Copyright (C) Andrew Tridgell 1995-1999 * * This software may be distributed either under the terms of the * BSD-style license that accompanies tcpdump or the GNU GPL version 2 * or later */ /* \summary: SMB/CIFS printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "smb.h" static const char tstr[] = "[|SMB]"; static int request = 0; static int unicodestr = 0; const u_char *startbuf = NULL; struct smbdescript { const char *req_f1; const char *req_f2; const char *rep_f1; const char *rep_f2; void (*fn)(netdissect_options *, const u_char *, const u_char *, const u_char *, const u_char *); }; struct smbdescriptint { const char *req_f1; const char *req_f2; const char *rep_f1; const char *rep_f2; void (*fn)(netdissect_options *, const u_char *, const u_char *, int, int); }; struct smbfns { int id; const char *name; int flags; struct smbdescript descript; }; struct smbfnsint { int id; const char *name; int flags; struct smbdescriptint descript; }; #define DEFDESCRIPT { NULL, NULL, NULL, NULL, NULL } #define FLG_CHAIN (1 << 0) static const struct smbfns * smbfind(int id, const struct smbfns *list) { int sindex; for (sindex = 0; list[sindex].name; sindex++) if (list[sindex].id == id) return(&list[sindex]); return(&list[0]); } static const struct smbfnsint * smbfindint(int id, const struct smbfnsint *list) { int sindex; for (sindex = 0; list[sindex].name; sindex++) if (list[sindex].id == id) return(&list[sindex]); return(&list[0]); } static void trans2_findfirst(netdissect_options *ndo, const u_char *param, const u_char *data, int pcnt, int dcnt) { const char *fmt; if (request) fmt = "Attribute=[A]\nSearchCount=[d]\nFlags=[w]\nLevel=[dP4]\nFile=[S]\n"; else fmt = "Handle=[w]\nCount=[d]\nEOS=[w]\nEoffset=[d]\nLastNameOfs=[w]\n"; smb_fdata(ndo, param, fmt, param + pcnt, unicodestr); if (dcnt) { ND_PRINT((ndo, "data:\n")); smb_print_data(ndo, data, dcnt); } } static void trans2_qfsinfo(netdissect_options *ndo, const u_char *param, const u_char *data, int pcnt, int dcnt) { static int level = 0; const char *fmt=""; if (request) { ND_TCHECK2(*param, 2); level = EXTRACT_LE_16BITS(param); fmt = "InfoLevel=[d]\n"; smb_fdata(ndo, param, fmt, param + pcnt, unicodestr); } else { switch (level) { case 1: fmt = "idFileSystem=[W]\nSectorUnit=[D]\nUnit=[D]\nAvail=[D]\nSectorSize=[d]\n"; break; case 2: fmt = "CreationTime=[T2]VolNameLength=[lb]\nVolumeLabel=[c]\n"; break; case 0x105: fmt = "Capabilities=[W]\nMaxFileLen=[D]\nVolNameLen=[lD]\nVolume=[C]\n"; break; default: fmt = "UnknownLevel\n"; break; } smb_fdata(ndo, data, fmt, data + dcnt, unicodestr); } if (dcnt) { ND_PRINT((ndo, "data:\n")); smb_print_data(ndo, data, dcnt); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static const struct smbfnsint trans2_fns[] = { { 0, "TRANSACT2_OPEN", 0, { "Flags2=[w]\nMode=[w]\nSearchAttrib=[A]\nAttrib=[A]\nTime=[T2]\nOFun=[w]\nSize=[D]\nRes=([w, w, w, w, w])\nPath=[S]", NULL, "Handle=[d]\nAttrib=[A]\nTime=[T2]\nSize=[D]\nAccess=[w]\nType=[w]\nState=[w]\nAction=[w]\nInode=[W]\nOffErr=[d]\n|EALength=[d]\n", NULL, NULL }}, { 1, "TRANSACT2_FINDFIRST", 0, { NULL, NULL, NULL, NULL, trans2_findfirst }}, { 2, "TRANSACT2_FINDNEXT", 0, DEFDESCRIPT }, { 3, "TRANSACT2_QFSINFO", 0, { NULL, NULL, NULL, NULL, trans2_qfsinfo }}, { 4, "TRANSACT2_SETFSINFO", 0, DEFDESCRIPT }, { 5, "TRANSACT2_QPATHINFO", 0, DEFDESCRIPT }, { 6, "TRANSACT2_SETPATHINFO", 0, DEFDESCRIPT }, { 7, "TRANSACT2_QFILEINFO", 0, DEFDESCRIPT }, { 8, "TRANSACT2_SETFILEINFO", 0, DEFDESCRIPT }, { 9, "TRANSACT2_FSCTL", 0, DEFDESCRIPT }, { 10, "TRANSACT2_IOCTL", 0, DEFDESCRIPT }, { 11, "TRANSACT2_FINDNOTIFYFIRST", 0, DEFDESCRIPT }, { 12, "TRANSACT2_FINDNOTIFYNEXT", 0, DEFDESCRIPT }, { 13, "TRANSACT2_MKDIR", 0, DEFDESCRIPT }, { -1, NULL, 0, DEFDESCRIPT } }; static void print_trans2(netdissect_options *ndo, const u_char *words, const u_char *dat, const u_char *buf, const u_char *maxbuf) { u_int bcc; static const struct smbfnsint *fn = &trans2_fns[0]; const u_char *data, *param; const u_char *w = words + 1; const char *f1 = NULL, *f2 = NULL; int pcnt, dcnt; ND_TCHECK(words[0]); if (request) { ND_TCHECK2(w[14 * 2], 2); pcnt = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); dcnt = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); fn = smbfindint(EXTRACT_LE_16BITS(w + 14 * 2), trans2_fns); } else { if (words[0] == 0) { ND_PRINT((ndo, "%s\n", fn->name)); ND_PRINT((ndo, "Trans2Interim\n")); return; } ND_TCHECK2(w[7 * 2], 2); pcnt = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); dcnt = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); } ND_PRINT((ndo, "%s param_length=%d data_length=%d\n", fn->name, pcnt, dcnt)); if (request) { if (words[0] == 8) { smb_fdata(ndo, words + 1, "Trans2Secondary\nTotParam=[d]\nTotData=[d]\nParamCnt=[d]\nParamOff=[d]\nParamDisp=[d]\nDataCnt=[d]\nDataOff=[d]\nDataDisp=[d]\nHandle=[d]\n", maxbuf, unicodestr); return; } else { smb_fdata(ndo, words + 1, "TotParam=[d]\nTotData=[d]\nMaxParam=[d]\nMaxData=[d]\nMaxSetup=[b][P1]\nFlags=[w]\nTimeOut=[D]\nRes1=[w]\nParamCnt=[d]\nParamOff=[d]\nDataCnt=[d]\nDataOff=[d]\nSetupCnt=[b][P1]\n", words + 1 + 14 * 2, unicodestr); } f1 = fn->descript.req_f1; f2 = fn->descript.req_f2; } else { smb_fdata(ndo, words + 1, "TotParam=[d]\nTotData=[d]\nRes1=[w]\nParamCnt=[d]\nParamOff=[d]\nParamDisp[d]\nDataCnt=[d]\nDataOff=[d]\nDataDisp=[d]\nSetupCnt=[b][P1]\n", words + 1 + 10 * 2, unicodestr); f1 = fn->descript.rep_f1; f2 = fn->descript.rep_f2; } ND_TCHECK2(*dat, 2); bcc = EXTRACT_LE_16BITS(dat); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (fn->descript.fn) (*fn->descript.fn)(ndo, param, data, pcnt, dcnt); else { smb_fdata(ndo, param, f1 ? f1 : "Parameters=\n", param + pcnt, unicodestr); smb_fdata(ndo, data, f2 ? f2 : "Data=\n", data + dcnt, unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_browse(netdissect_options *ndo, const u_char *param, int paramlen, const u_char *data, int datalen) { const u_char *maxbuf = data + datalen; int command; ND_TCHECK(data[0]); command = data[0]; smb_fdata(ndo, param, "BROWSE PACKET\n|Param ", param+paramlen, unicodestr); switch (command) { case 0xF: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (LocalMasterAnnouncement)\nUpdateCount=[w]\nRes1=[B]\nAnnounceInterval=[d]\nName=[n2]\nMajorVersion=[B]\nMinorVersion=[B]\nServerType=[W]\nElectionVersion=[w]\nBrowserConstant=[w]\n", maxbuf, unicodestr); break; case 0x1: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (HostAnnouncement)\nUpdateCount=[w]\nRes1=[B]\nAnnounceInterval=[d]\nName=[n2]\nMajorVersion=[B]\nMinorVersion=[B]\nServerType=[W]\nElectionVersion=[w]\nBrowserConstant=[w]\n", maxbuf, unicodestr); break; case 0x2: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (AnnouncementRequest)\nFlags=[B]\nReplySystemName=[S]\n", maxbuf, unicodestr); break; case 0xc: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (WorkgroupAnnouncement)\nUpdateCount=[w]\nRes1=[B]\nAnnounceInterval=[d]\nName=[n2]\nMajorVersion=[B]\nMinorVersion=[B]\nServerType=[W]\nCommentPointer=[W]\nServerName=[S]\n", maxbuf, unicodestr); break; case 0x8: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (ElectionFrame)\nElectionVersion=[B]\nOSSummary=[W]\nUptime=[(W, W)]\nServerName=[S]\n", maxbuf, unicodestr); break; case 0xb: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (BecomeBackupBrowser)\nName=[S]\n", maxbuf, unicodestr); break; case 0x9: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (GetBackupList)\nListCount?=[B]\nToken=[W]\n", maxbuf, unicodestr); break; case 0xa: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (BackupListResponse)\nServerCount?=[B]\nToken=[W]\n*Name=[S]\n", maxbuf, unicodestr); break; case 0xd: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (MasterAnnouncement)\nMasterName=[S]\n", maxbuf, unicodestr); break; case 0xe: data = smb_fdata(ndo, data, "BROWSE PACKET:\nType=[B] (ResetBrowser)\nOptions=[B]\n", maxbuf, unicodestr); break; default: data = smb_fdata(ndo, data, "Unknown Browser Frame ", maxbuf, unicodestr); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_ipc(netdissect_options *ndo, const u_char *param, int paramlen, const u_char *data, int datalen) { if (paramlen) smb_fdata(ndo, param, "Command=[w]\nStr1=[S]\nStr2=[S]\n", param + paramlen, unicodestr); if (datalen) smb_fdata(ndo, data, "IPC ", data + datalen, unicodestr); } static void print_trans(netdissect_options *ndo, const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf) { u_int bcc; const char *f1, *f2, *f3, *f4; const u_char *data, *param; const u_char *w = words + 1; int datalen, paramlen; if (request) { ND_TCHECK2(w[12 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 9 * 2); param = buf + EXTRACT_LE_16BITS(w + 10 * 2); datalen = EXTRACT_LE_16BITS(w + 11 * 2); data = buf + EXTRACT_LE_16BITS(w + 12 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n"; f2 = "|Name=[S]\n"; f3 = "|Param "; f4 = "|Data "; } else { ND_TCHECK2(w[7 * 2], 2); paramlen = EXTRACT_LE_16BITS(w + 3 * 2); param = buf + EXTRACT_LE_16BITS(w + 4 * 2); datalen = EXTRACT_LE_16BITS(w + 6 * 2); data = buf + EXTRACT_LE_16BITS(w + 7 * 2); f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n"; f2 = "|Unknown "; f3 = "|Param "; f4 = "|Data "; } smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf), unicodestr); ND_TCHECK2(*data1, 2); bcc = EXTRACT_LE_16BITS(data1); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr); #define MAILSLOT_BROWSE_STR "\\MAILSLOT\\BROWSE" ND_TCHECK2(*(data1 + 2), strlen(MAILSLOT_BROWSE_STR) + 1); if (strcmp((const char *)(data1 + 2), MAILSLOT_BROWSE_STR) == 0) { print_browse(ndo, param, paramlen, data, datalen); return; } #undef MAILSLOT_BROWSE_STR #define PIPE_LANMAN_STR "\\PIPE\\LANMAN" ND_TCHECK2(*(data1 + 2), strlen(PIPE_LANMAN_STR) + 1); if (strcmp((const char *)(data1 + 2), PIPE_LANMAN_STR) == 0) { print_ipc(ndo, param, paramlen, data, datalen); return; } #undef PIPE_LANMAN_STR if (paramlen) smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr); if (datalen) smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_negprot(netdissect_options *ndo, const u_char *words, const u_char *data, const u_char *buf _U_, const u_char *maxbuf) { u_int wct, bcc; const char *f1 = NULL, *f2 = NULL; ND_TCHECK(words[0]); wct = words[0]; if (request) f2 = "*|Dialect=[Y]\n"; else { if (wct == 1) f1 = "Core Protocol\nDialectIndex=[d]"; else if (wct == 17) f1 = "NT1 Protocol\nDialectIndex=[d]\nSecMode=[B]\nMaxMux=[d]\nNumVcs=[d]\nMaxBuffer=[D]\nRawSize=[D]\nSessionKey=[W]\nCapabilities=[W]\nServerTime=[T3]TimeZone=[d]\nCryptKey="; else if (wct == 13) f1 = "Coreplus/Lanman1/Lanman2 Protocol\nDialectIndex=[d]\nSecMode=[w]\nMaxXMit=[d]\nMaxMux=[d]\nMaxVcs=[d]\nBlkMode=[w]\nSessionKey=[W]\nServerTime=[T1]TimeZone=[d]\nRes=[W]\nCryptKey="; } if (f1) smb_fdata(ndo, words + 1, f1, min(words + 1 + wct * 2, maxbuf), unicodestr); else smb_print_data(ndo, words + 1, min(wct * 2, PTR_DIFF(maxbuf, words + 1))); ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { if (f2) smb_fdata(ndo, data + 2, f2, min(data + 2 + EXTRACT_LE_16BITS(data), maxbuf), unicodestr); else smb_print_data(ndo, data + 2, min(EXTRACT_LE_16BITS(data), PTR_DIFF(maxbuf, data + 2))); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_sesssetup(netdissect_options *ndo, const u_char *words, const u_char *data, const u_char *buf _U_, const u_char *maxbuf) { u_int wct, bcc; const char *f1 = NULL, *f2 = NULL; ND_TCHECK(words[0]); wct = words[0]; if (request) { if (wct == 10) f1 = "Com2=[w]\nOff2=[d]\nBufSize=[d]\nMpxMax=[d]\nVcNum=[d]\nSessionKey=[W]\nPassLen=[d]\nCryptLen=[d]\nCryptOff=[d]\nPass&Name=\n"; else f1 = "Com2=[B]\nRes1=[B]\nOff2=[d]\nMaxBuffer=[d]\nMaxMpx=[d]\nVcNumber=[d]\nSessionKey=[W]\nCaseInsensitivePasswordLength=[d]\nCaseSensitivePasswordLength=[d]\nRes=[W]\nCapabilities=[W]\nPass1&Pass2&Account&Domain&OS&LanMan=\n"; } else { if (wct == 3) { f1 = "Com2=[w]\nOff2=[d]\nAction=[w]\n"; } else if (wct == 13) { f1 = "Com2=[B]\nRes=[B]\nOff2=[d]\nAction=[w]\n"; f2 = "NativeOS=[S]\nNativeLanMan=[S]\nPrimaryDomain=[S]\n"; } } if (f1) smb_fdata(ndo, words + 1, f1, min(words + 1 + wct * 2, maxbuf), unicodestr); else smb_print_data(ndo, words + 1, min(wct * 2, PTR_DIFF(maxbuf, words + 1))); ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { if (f2) smb_fdata(ndo, data + 2, f2, min(data + 2 + EXTRACT_LE_16BITS(data), maxbuf), unicodestr); else smb_print_data(ndo, data + 2, min(EXTRACT_LE_16BITS(data), PTR_DIFF(maxbuf, data + 2))); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static void print_lockingandx(netdissect_options *ndo, const u_char *words, const u_char *data, const u_char *buf _U_, const u_char *maxbuf) { u_int wct, bcc; const u_char *maxwords; const char *f1 = NULL, *f2 = NULL; ND_TCHECK(words[0]); wct = words[0]; if (request) { f1 = "Com2=[w]\nOff2=[d]\nHandle=[d]\nLockType=[w]\nTimeOut=[D]\nUnlockCount=[d]\nLockCount=[d]\n"; ND_TCHECK(words[7]); if (words[7] & 0x10) f2 = "*Process=[d]\n[P2]Offset=[M]\nLength=[M]\n"; else f2 = "*Process=[d]\nOffset=[D]\nLength=[D]\n"; } else { f1 = "Com2=[w]\nOff2=[d]\n"; } maxwords = min(words + 1 + wct * 2, maxbuf); if (wct) smb_fdata(ndo, words + 1, f1, maxwords, unicodestr); ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (bcc > 0) { if (f2) smb_fdata(ndo, data + 2, f2, min(data + 2 + EXTRACT_LE_16BITS(data), maxbuf), unicodestr); else smb_print_data(ndo, data + 2, min(EXTRACT_LE_16BITS(data), PTR_DIFF(maxbuf, data + 2))); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static const struct smbfns smb_fns[] = { { -1, "SMBunknown", 0, DEFDESCRIPT }, { SMBtcon, "SMBtcon", 0, { NULL, "Path=[Z]\nPassword=[Z]\nDevice=[Z]\n", "MaxXmit=[d]\nTreeId=[d]\n", NULL, NULL } }, { SMBtdis, "SMBtdis", 0, DEFDESCRIPT }, { SMBexit, "SMBexit", 0, DEFDESCRIPT }, { SMBioctl, "SMBioctl", 0, DEFDESCRIPT }, { SMBecho, "SMBecho", 0, { "ReverbCount=[d]\n", NULL, "SequenceNum=[d]\n", NULL, NULL } }, { SMBulogoffX, "SMBulogoffX", FLG_CHAIN, DEFDESCRIPT }, { SMBgetatr, "SMBgetatr", 0, { NULL, "Path=[Z]\n", "Attribute=[A]\nTime=[T2]Size=[D]\nRes=([w,w,w,w,w])\n", NULL, NULL } }, { SMBsetatr, "SMBsetatr", 0, { "Attribute=[A]\nTime=[T2]Res=([w,w,w,w,w])\n", "Path=[Z]\n", NULL, NULL, NULL } }, { SMBchkpth, "SMBchkpth", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBsearch, "SMBsearch", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBopen, "SMBopen", 0, { "Mode=[w]\nAttribute=[A]\n", "Path=[Z]\n", "Handle=[d]\nOAttrib=[A]\nTime=[T2]Size=[D]\nAccess=[w]\n", NULL, NULL } }, { SMBcreate, "SMBcreate", 0, { "Attrib=[A]\nTime=[T2]", "Path=[Z]\n", "Handle=[d]\n", NULL, NULL } }, { SMBmknew, "SMBmknew", 0, { "Attrib=[A]\nTime=[T2]", "Path=[Z]\n", "Handle=[d]\n", NULL, NULL } }, { SMBunlink, "SMBunlink", 0, { "Attrib=[A]\n", "Path=[Z]\n", NULL, NULL, NULL } }, { SMBread, "SMBread", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\nRes=([w,w,w,w])\n", NULL, NULL } }, { SMBwrite, "SMBwrite", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\n", NULL, NULL } }, { SMBclose, "SMBclose", 0, { "Handle=[d]\nTime=[T2]", NULL, NULL, NULL, NULL } }, { SMBmkdir, "SMBmkdir", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBrmdir, "SMBrmdir", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBdskattr, "SMBdskattr", 0, { NULL, NULL, "TotalUnits=[d]\nBlocksPerUnit=[d]\nBlockSize=[d]\nFreeUnits=[d]\nMedia=[w]\n", NULL, NULL } }, { SMBmv, "SMBmv", 0, { "Attrib=[A]\n", "OldPath=[Z]\nNewPath=[Z]\n", NULL, NULL, NULL } }, /* * this is a Pathworks specific call, allowing the * changing of the root path */ { pSETDIR, "SMBsetdir", 0, { NULL, "Path=[Z]\n", NULL, NULL, NULL } }, { SMBlseek, "SMBlseek", 0, { "Handle=[d]\nMode=[w]\nOffset=[D]\n", "Offset=[D]\n", NULL, NULL, NULL } }, { SMBflush, "SMBflush", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsplopen, "SMBsplopen", 0, { "SetupLen=[d]\nMode=[w]\n", "Ident=[Z]\n", "Handle=[d]\n", NULL, NULL } }, { SMBsplclose, "SMBsplclose", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsplretq, "SMBsplretq", 0, { "MaxCount=[d]\nStartIndex=[d]\n", NULL, "Count=[d]\nIndex=[d]\n", "*Time=[T2]Status=[B]\nJobID=[d]\nSize=[D]\nRes=[B]Name=[s16]\n", NULL } }, { SMBsplwr, "SMBsplwr", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBlock, "SMBlock", 0, { "Handle=[d]\nCount=[D]\nOffset=[D]\n", NULL, NULL, NULL, NULL } }, { SMBunlock, "SMBunlock", 0, { "Handle=[d]\nCount=[D]\nOffset=[D]\n", NULL, NULL, NULL, NULL } }, /* CORE+ PROTOCOL FOLLOWS */ { SMBreadbraw, "SMBreadbraw", 0, { "Handle=[d]\nOffset=[D]\nMaxCount=[d]\nMinCount=[d]\nTimeOut=[D]\nRes=[d]\n", NULL, NULL, NULL, NULL } }, { SMBwritebraw, "SMBwritebraw", 0, { "Handle=[d]\nTotalCount=[d]\nRes=[w]\nOffset=[D]\nTimeOut=[D]\nWMode=[w]\nRes2=[W]\n|DataSize=[d]\nDataOff=[d]\n", NULL, "WriteRawAck", NULL, NULL } }, { SMBwritec, "SMBwritec", 0, { NULL, NULL, "Count=[d]\n", NULL, NULL } }, { SMBwriteclose, "SMBwriteclose", 0, { "Handle=[d]\nCount=[d]\nOffset=[D]\nTime=[T2]Res=([w,w,w,w,w,w])", NULL, "Count=[d]\n", NULL, NULL } }, { SMBlockread, "SMBlockread", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\nRes=([w,w,w,w])\n", NULL, NULL } }, { SMBwriteunlock, "SMBwriteunlock", 0, { "Handle=[d]\nByteCount=[d]\nOffset=[D]\nCountLeft=[d]\n", NULL, "Count=[d]\n", NULL, NULL } }, { SMBreadBmpx, "SMBreadBmpx", 0, { "Handle=[d]\nOffset=[D]\nMaxCount=[d]\nMinCount=[d]\nTimeOut=[D]\nRes=[w]\n", NULL, "Offset=[D]\nTotCount=[d]\nRemaining=[d]\nRes=([w,w])\nDataSize=[d]\nDataOff=[d]\n", NULL, NULL } }, { SMBwriteBmpx, "SMBwriteBmpx", 0, { "Handle=[d]\nTotCount=[d]\nRes=[w]\nOffset=[D]\nTimeOut=[D]\nWMode=[w]\nRes2=[W]\nDataSize=[d]\nDataOff=[d]\n", NULL, "Remaining=[d]\n", NULL, NULL } }, { SMBwriteBs, "SMBwriteBs", 0, { "Handle=[d]\nTotCount=[d]\nOffset=[D]\nRes=[W]\nDataSize=[d]\nDataOff=[d]\n", NULL, "Count=[d]\n", NULL, NULL } }, { SMBsetattrE, "SMBsetattrE", 0, { "Handle=[d]\nCreationTime=[T2]AccessTime=[T2]ModifyTime=[T2]", NULL, NULL, NULL, NULL } }, { SMBgetattrE, "SMBgetattrE", 0, { "Handle=[d]\n", NULL, "CreationTime=[T2]AccessTime=[T2]ModifyTime=[T2]Size=[D]\nAllocSize=[D]\nAttribute=[A]\n", NULL, NULL } }, { SMBtranss, "SMBtranss", 0, DEFDESCRIPT }, { SMBioctls, "SMBioctls", 0, DEFDESCRIPT }, { SMBcopy, "SMBcopy", 0, { "TreeID2=[d]\nOFun=[w]\nFlags=[w]\n", "Path=[S]\nNewPath=[S]\n", "CopyCount=[d]\n", "|ErrStr=[S]\n", NULL } }, { SMBmove, "SMBmove", 0, { "TreeID2=[d]\nOFun=[w]\nFlags=[w]\n", "Path=[S]\nNewPath=[S]\n", "MoveCount=[d]\n", "|ErrStr=[S]\n", NULL } }, { SMBopenX, "SMBopenX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nFlags=[w]\nMode=[w]\nSearchAttrib=[A]\nAttrib=[A]\nTime=[T2]OFun=[w]\nSize=[D]\nTimeOut=[D]\nRes=[W]\n", "Path=[S]\n", "Com2=[w]\nOff2=[d]\nHandle=[d]\nAttrib=[A]\nTime=[T2]Size=[D]\nAccess=[w]\nType=[w]\nState=[w]\nAction=[w]\nFileID=[W]\nRes=[w]\n", NULL, NULL } }, { SMBreadX, "SMBreadX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nHandle=[d]\nOffset=[D]\nMaxCount=[d]\nMinCount=[d]\nTimeOut=[D]\nCountLeft=[d]\n", NULL, "Com2=[w]\nOff2=[d]\nRemaining=[d]\nRes=[W]\nDataSize=[d]\nDataOff=[d]\nRes=([w,w,w,w])\n", NULL, NULL } }, { SMBwriteX, "SMBwriteX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nHandle=[d]\nOffset=[D]\nTimeOut=[D]\nWMode=[w]\nCountLeft=[d]\nRes=[w]\nDataSize=[d]\nDataOff=[d]\n", NULL, "Com2=[w]\nOff2=[d]\nCount=[d]\nRemaining=[d]\nRes=[W]\n", NULL, NULL } }, { SMBffirst, "SMBffirst", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBfunique, "SMBfunique", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBfclose, "SMBfclose", 0, { "Count=[d]\nAttrib=[A]\n", "Path=[Z]\nBlkType=[B]\nBlkLen=[d]\n|Res1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\n", "Count=[d]\n", "BlkType=[B]\nBlkLen=[d]\n*\nRes1=[B]\nMask=[s11]\nSrv1=[B]\nDirIndex=[d]\nSrv2=[w]\nRes2=[W]\nAttrib=[a]\nTime=[T1]Size=[D]\nName=[s13]\n", NULL } }, { SMBfindnclose, "SMBfindnclose", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBfindclose, "SMBfindclose", 0, { "Handle=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsends, "SMBsends", 0, { NULL, "Source=[Z]\nDest=[Z]\n", NULL, NULL, NULL } }, { SMBsendstrt, "SMBsendstrt", 0, { NULL, "Source=[Z]\nDest=[Z]\n", "GroupID=[d]\n", NULL, NULL } }, { SMBsendend, "SMBsendend", 0, { "GroupID=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsendtxt, "SMBsendtxt", 0, { "GroupID=[d]\n", NULL, NULL, NULL, NULL } }, { SMBsendb, "SMBsendb", 0, { NULL, "Source=[Z]\nDest=[Z]\n", NULL, NULL, NULL } }, { SMBfwdname, "SMBfwdname", 0, DEFDESCRIPT }, { SMBcancelf, "SMBcancelf", 0, DEFDESCRIPT }, { SMBgetmac, "SMBgetmac", 0, DEFDESCRIPT }, { SMBnegprot, "SMBnegprot", 0, { NULL, NULL, NULL, NULL, print_negprot } }, { SMBsesssetupX, "SMBsesssetupX", FLG_CHAIN, { NULL, NULL, NULL, NULL, print_sesssetup } }, { SMBtconX, "SMBtconX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nFlags=[w]\nPassLen=[d]\nPasswd&Path&Device=\n", NULL, "Com2=[w]\nOff2=[d]\n", "ServiceType=[R]\n", NULL } }, { SMBlockingX, "SMBlockingX", FLG_CHAIN, { NULL, NULL, NULL, NULL, print_lockingandx } }, { SMBtrans2, "SMBtrans2", 0, { NULL, NULL, NULL, NULL, print_trans2 } }, { SMBtranss2, "SMBtranss2", 0, DEFDESCRIPT }, { SMBctemp, "SMBctemp", 0, DEFDESCRIPT }, { SMBreadBs, "SMBreadBs", 0, DEFDESCRIPT }, { SMBtrans, "SMBtrans", 0, { NULL, NULL, NULL, NULL, print_trans } }, { SMBnttrans, "SMBnttrans", 0, DEFDESCRIPT }, { SMBnttranss, "SMBnttranss", 0, DEFDESCRIPT }, { SMBntcreateX, "SMBntcreateX", FLG_CHAIN, { "Com2=[w]\nOff2=[d]\nRes=[b]\nNameLen=[ld]\nFlags=[W]\nRootDirectoryFid=[D]\nAccessMask=[W]\nAllocationSize=[L]\nExtFileAttributes=[W]\nShareAccess=[W]\nCreateDisposition=[W]\nCreateOptions=[W]\nImpersonationLevel=[W]\nSecurityFlags=[b]\n", "Path=[C]\n", "Com2=[w]\nOff2=[d]\nOplockLevel=[b]\nFid=[d]\nCreateAction=[W]\nCreateTime=[T3]LastAccessTime=[T3]LastWriteTime=[T3]ChangeTime=[T3]ExtFileAttributes=[W]\nAllocationSize=[L]\nEndOfFile=[L]\nFileType=[w]\nDeviceState=[w]\nDirectory=[b]\n", NULL, NULL } }, { SMBntcancel, "SMBntcancel", 0, DEFDESCRIPT }, { -1, NULL, 0, DEFDESCRIPT } }; /* * print a SMB message */ static void print_smb(netdissect_options *ndo, const u_char *buf, const u_char *maxbuf) { uint16_t flags2; int nterrcodes; int command; uint32_t nterror; const u_char *words, *maxwords, *data; const struct smbfns *fn; const char *fmt_smbheader = "[P4]SMB Command = [B]\nError class = [BP1]\nError code = [d]\nFlags1 = [B]\nFlags2 = [B][P13]\nTree ID = [d]\nProc ID = [d]\nUID = [d]\nMID = [d]\nWord Count = [b]\n"; int smboffset; ND_TCHECK(buf[9]); request = (buf[9] & 0x80) ? 0 : 1; startbuf = buf; command = buf[4]; fn = smbfind(command, smb_fns); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n")); ND_PRINT((ndo, "SMB PACKET: %s (%s)\n", fn->name, request ? "REQUEST" : "REPLY")); if (ndo->ndo_vflag < 2) return; ND_TCHECK_16BITS(&buf[10]); flags2 = EXTRACT_LE_16BITS(&buf[10]); unicodestr = flags2 & 0x8000; nterrcodes = flags2 & 0x4000; /* print out the header */ smb_fdata(ndo, buf, fmt_smbheader, buf + 33, unicodestr); if (nterrcodes) { nterror = EXTRACT_LE_32BITS(&buf[5]); if (nterror) ND_PRINT((ndo, "NTError = %s\n", nt_errstr(nterror))); } else { if (buf[5]) ND_PRINT((ndo, "SMBError = %s\n", smb_errstr(buf[5], EXTRACT_LE_16BITS(&buf[7])))); } smboffset = 32; for (;;) { const char *f1, *f2; int wct; u_int bcc; int newsmboffset; words = buf + smboffset; ND_TCHECK(words[0]); wct = words[0]; data = words + 1 + wct * 2; maxwords = min(data, maxbuf); if (request) { f1 = fn->descript.req_f1; f2 = fn->descript.req_f2; } else { f1 = fn->descript.rep_f1; f2 = fn->descript.rep_f2; } if (fn->descript.fn) (*fn->descript.fn)(ndo, words, data, buf, maxbuf); else { if (wct) { if (f1) smb_fdata(ndo, words + 1, f1, words + 1 + wct * 2, unicodestr); else { int i; int v; for (i = 0; &words[1 + 2 * i] < maxwords; i++) { ND_TCHECK2(words[1 + 2 * i], 2); v = EXTRACT_LE_16BITS(words + 1 + 2 * i); ND_PRINT((ndo, "smb_vwv[%d]=%d (0x%X)\n", i, v, v)); } } } ND_TCHECK2(*data, 2); bcc = EXTRACT_LE_16BITS(data); ND_PRINT((ndo, "smb_bcc=%u\n", bcc)); if (f2) { if (bcc > 0) smb_fdata(ndo, data + 2, f2, data + 2 + bcc, unicodestr); } else { if (bcc > 0) { ND_PRINT((ndo, "smb_buf[]=\n")); smb_print_data(ndo, data + 2, min(bcc, PTR_DIFF(maxbuf, data + 2))); } } } if ((fn->flags & FLG_CHAIN) == 0) break; if (wct == 0) break; ND_TCHECK(words[1]); command = words[1]; if (command == 0xFF) break; ND_TCHECK2(words[3], 2); newsmboffset = EXTRACT_LE_16BITS(words + 3); fn = smbfind(command, smb_fns); ND_PRINT((ndo, "\nSMB PACKET: %s (%s) (CHAINED)\n", fn->name, request ? "REQUEST" : "REPLY")); if (newsmboffset <= smboffset) { ND_PRINT((ndo, "Bad andX offset: %u <= %u\n", newsmboffset, smboffset)); break; } smboffset = newsmboffset; } ND_PRINT((ndo, "\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * print a NBT packet received across tcp on port 139 */ void nbt_tcp_print(netdissect_options *ndo, const u_char *data, int length) { int caplen; int type; u_int nbt_len; const u_char *maxbuf; if (length < 4) goto trunc; if (ndo->ndo_snapend < data) goto trunc; caplen = ndo->ndo_snapend - data; if (caplen < 4) goto trunc; maxbuf = data + caplen; ND_TCHECK_8BITS(data); type = data[0]; ND_TCHECK_16BITS(data + 2); nbt_len = EXTRACT_16BITS(data + 2); length -= 4; caplen -= 4; startbuf = data; if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, " NBT Session Packet: ")); switch (type) { case 0x00: ND_PRINT((ndo, "Session Message")); break; case 0x81: ND_PRINT((ndo, "Session Request")); break; case 0x82: ND_PRINT((ndo, "Session Granted")); break; case 0x83: { int ecode; if (nbt_len < 4) goto trunc; if (length < 4) goto trunc; if (caplen < 4) goto trunc; ecode = data[4]; ND_PRINT((ndo, "Session Reject, ")); switch (ecode) { case 0x80: ND_PRINT((ndo, "Not listening on called name")); break; case 0x81: ND_PRINT((ndo, "Not listening for calling name")); break; case 0x82: ND_PRINT((ndo, "Called name not present")); break; case 0x83: ND_PRINT((ndo, "Called name present, but insufficient resources")); break; default: ND_PRINT((ndo, "Unspecified error 0x%X", ecode)); break; } } break; case 0x85: ND_PRINT((ndo, "Session Keepalive")); break; default: data = smb_fdata(ndo, data, "Unknown packet type [rB]", maxbuf, 0); break; } } else { ND_PRINT((ndo, "\n>>> NBT Session Packet\n")); switch (type) { case 0x00: data = smb_fdata(ndo, data, "[P1]NBT Session Message\nFlags=[B]\nLength=[rd]\n", data + 4, 0); if (data == NULL) break; if (nbt_len >= 4 && caplen >= 4 && memcmp(data,"\377SMB",4) == 0) { if ((int)nbt_len > caplen) { if ((int)nbt_len > length) ND_PRINT((ndo, "WARNING: Packet is continued in later TCP segments\n")); else ND_PRINT((ndo, "WARNING: Short packet. Try increasing the snap length by %d\n", nbt_len - caplen)); } print_smb(ndo, data, maxbuf > data + nbt_len ? data + nbt_len : maxbuf); } else ND_PRINT((ndo, "Session packet:(raw data or continuation?)\n")); break; case 0x81: data = smb_fdata(ndo, data, "[P1]NBT Session Request\nFlags=[B]\nLength=[rd]\nDestination=[n1]\nSource=[n1]\n", maxbuf, 0); break; case 0x82: data = smb_fdata(ndo, data, "[P1]NBT Session Granted\nFlags=[B]\nLength=[rd]\n", maxbuf, 0); break; case 0x83: { const u_char *origdata; int ecode; origdata = data; data = smb_fdata(ndo, data, "[P1]NBT SessionReject\nFlags=[B]\nLength=[rd]\nReason=[B]\n", maxbuf, 0); if (data == NULL) break; if (nbt_len >= 1 && caplen >= 1) { ecode = origdata[4]; switch (ecode) { case 0x80: ND_PRINT((ndo, "Not listening on called name\n")); break; case 0x81: ND_PRINT((ndo, "Not listening for calling name\n")); break; case 0x82: ND_PRINT((ndo, "Called name not present\n")); break; case 0x83: ND_PRINT((ndo, "Called name present, but insufficient resources\n")); break; default: ND_PRINT((ndo, "Unspecified error 0x%X\n", ecode)); break; } } } break; case 0x85: data = smb_fdata(ndo, data, "[P1]NBT Session Keepalive\nFlags=[B]\nLength=[rd]\n", maxbuf, 0); break; default: data = smb_fdata(ndo, data, "NBT - Unknown packet type\nType=[B]\n", maxbuf, 0); break; } ND_PRINT((ndo, "\n")); } return; trunc: ND_PRINT((ndo, "%s", tstr)); } static const struct tok opcode_str[] = { { 0, "QUERY" }, { 5, "REGISTRATION" }, { 6, "RELEASE" }, { 7, "WACK" }, { 8, "REFRESH(8)" }, { 9, "REFRESH" }, { 15, "MULTIHOMED REGISTRATION" }, { 0, NULL } }; /* * print a NBT packet received across udp on port 137 */ void nbt_udp137_print(netdissect_options *ndo, const u_char *data, int length) { const u_char *maxbuf = data + length; int name_trn_id, response, opcode, nm_flags, rcode; int qdcount, ancount, nscount, arcount; const u_char *p; int total, i; ND_TCHECK2(data[10], 2); name_trn_id = EXTRACT_16BITS(data); response = (data[2] >> 7); opcode = (data[2] >> 3) & 0xF; nm_flags = ((data[2] & 0x7) << 4) + (data[3] >> 4); rcode = data[3] & 0xF; qdcount = EXTRACT_16BITS(data + 4); ancount = EXTRACT_16BITS(data + 6); nscount = EXTRACT_16BITS(data + 8); arcount = EXTRACT_16BITS(data + 10); startbuf = data; if (maxbuf <= data) return; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n>>> ")); ND_PRINT((ndo, "NBT UDP PACKET(137): %s", tok2str(opcode_str, "OPUNKNOWN", opcode))); if (response) { ND_PRINT((ndo, "; %s", rcode ? "NEGATIVE" : "POSITIVE")); } ND_PRINT((ndo, "; %s; %s", response ? "RESPONSE" : "REQUEST", (nm_flags & 1) ? "BROADCAST" : "UNICAST")); if (ndo->ndo_vflag < 2) return; ND_PRINT((ndo, "\nTrnID=0x%X\nOpCode=%d\nNmFlags=0x%X\nRcode=%d\nQueryCount=%d\nAnswerCount=%d\nAuthorityCount=%d\nAddressRecCount=%d\n", name_trn_id, opcode, nm_flags, rcode, qdcount, ancount, nscount, arcount)); p = data + 12; total = ancount + nscount + arcount; if (qdcount > 100 || total > 100) { ND_PRINT((ndo, "Corrupt packet??\n")); return; } if (qdcount) { ND_PRINT((ndo, "QuestionRecords:\n")); for (i = 0; i < qdcount; i++) { p = smb_fdata(ndo, p, "|Name=[n1]\nQuestionType=[rw]\nQuestionClass=[rw]\n#", maxbuf, 0); if (p == NULL) goto out; } } if (total) { ND_PRINT((ndo, "\nResourceRecords:\n")); for (i = 0; i < total; i++) { int rdlen; int restype; p = smb_fdata(ndo, p, "Name=[n1]\n#", maxbuf, 0); if (p == NULL) goto out; ND_TCHECK_16BITS(p); restype = EXTRACT_16BITS(p); p = smb_fdata(ndo, p, "ResType=[rw]\nResClass=[rw]\nTTL=[rD]\n", p + 8, 0); if (p == NULL) goto out; ND_TCHECK_16BITS(p); rdlen = EXTRACT_16BITS(p); ND_PRINT((ndo, "ResourceLength=%d\nResourceData=\n", rdlen)); p += 2; if (rdlen == 6) { p = smb_fdata(ndo, p, "AddrType=[rw]\nAddress=[b.b.b.b]\n", p + rdlen, 0); if (p == NULL) goto out; } else { if (restype == 0x21) { int numnames; ND_TCHECK(*p); numnames = p[0]; p = smb_fdata(ndo, p, "NumNames=[B]\n", p + 1, 0); if (p == NULL) goto out; while (numnames--) { p = smb_fdata(ndo, p, "Name=[n2]\t#", maxbuf, 0); if (p == NULL) goto out; ND_TCHECK(*p); if (p[0] & 0x80) ND_PRINT((ndo, "<GROUP> ")); switch (p[0] & 0x60) { case 0x00: ND_PRINT((ndo, "B ")); break; case 0x20: ND_PRINT((ndo, "P ")); break; case 0x40: ND_PRINT((ndo, "M ")); break; case 0x60: ND_PRINT((ndo, "_ ")); break; } if (p[0] & 0x10) ND_PRINT((ndo, "<DEREGISTERING> ")); if (p[0] & 0x08) ND_PRINT((ndo, "<CONFLICT> ")); if (p[0] & 0x04) ND_PRINT((ndo, "<ACTIVE> ")); if (p[0] & 0x02) ND_PRINT((ndo, "<PERMANENT> ")); ND_PRINT((ndo, "\n")); p += 2; } } else { smb_print_data(ndo, p, min(rdlen, length - (p - data))); p += rdlen; } } } } if (p < maxbuf) smb_fdata(ndo, p, "AdditionalData:\n", maxbuf, 0); out: ND_PRINT((ndo, "\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * Print an SMB-over-TCP packet received across tcp on port 445 */ void smb_tcp_print(netdissect_options *ndo, const u_char * data, int length) { int caplen; u_int smb_len; const u_char *maxbuf; if (length < 4) goto trunc; if (ndo->ndo_snapend < data) goto trunc; caplen = ndo->ndo_snapend - data; if (caplen < 4) goto trunc; maxbuf = data + caplen; smb_len = EXTRACT_24BITS(data + 1); length -= 4; caplen -= 4; startbuf = data; data += 4; if (smb_len >= 4 && caplen >= 4 && memcmp(data,"\377SMB",4) == 0) { if ((int)smb_len > caplen) { if ((int)smb_len > length) ND_PRINT((ndo, " WARNING: Packet is continued in later TCP segments\n")); else ND_PRINT((ndo, " WARNING: Short packet. Try increasing the snap length by %d\n", smb_len - caplen)); } else ND_PRINT((ndo, " ")); print_smb(ndo, data, maxbuf > data + smb_len ? data + smb_len : maxbuf); } else ND_PRINT((ndo, " SMB-over-TCP packet:(raw data or continuation?)\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * print a NBT packet received across udp on port 138 */ void nbt_udp138_print(netdissect_options *ndo, const u_char *data, int length) { const u_char *maxbuf = data + length; if (maxbuf > ndo->ndo_snapend) maxbuf = ndo->ndo_snapend; if (maxbuf <= data) return; startbuf = data; if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, "NBT UDP PACKET(138)")); return; } data = smb_fdata(ndo, data, "\n>>> NBT UDP PACKET(138) Res=[rw] ID=[rw] IP=[b.b.b.b] Port=[rd] Length=[rd] Res2=[rw]\nSourceName=[n1]\nDestName=[n1]\n#", maxbuf, 0); if (data != NULL) { /* If there isn't enough data for "\377SMB", don't check for it. */ if (&data[3] >= maxbuf) goto out; if (memcmp(data, "\377SMB",4) == 0) print_smb(ndo, data, maxbuf); } out: ND_PRINT((ndo, "\n")); } /* print netbeui frames */ static struct nbf_strings { const char *name; const char *nonverbose; const char *verbose; } nbf_strings[0x20] = { { "Add Group Name Query", ", [P23]Name to add=[n2]#", "[P5]ResponseCorrelator=[w]\n[P16]Name to add=[n2]\n" }, { "Add Name Query", ", [P23]Name to add=[n2]#", "[P5]ResponseCorrelator=[w]\n[P16]Name to add=[n2]\n" }, { "Name In Conflict", NULL, NULL }, { "Status Query", NULL, NULL }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Terminate Trace", NULL, NULL }, { "Datagram", NULL, "[P7]Destination=[n2]\nSource=[n2]\n" }, { "Broadcast Datagram", NULL, "[P7]Destination=[n2]\nSource=[n2]\n" }, { "Name Query", ", [P7]Name=[n2]#", "[P1]SessionNumber=[B]\nNameType=[B][P2]\nResponseCorrelator=[w]\nName=[n2]\nName of sender=[n2]\n" }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Add Name Response", ", [P1]GroupName=[w] [P4]Destination=[n2] Source=[n2]#", "AddNameInProcess=[B]\nGroupName=[w]\nTransmitCorrelator=[w][P2]\nDestination=[n2]\nSource=[n2]\n" }, { "Name Recognized", NULL, "[P1]Data2=[w]\nTransmitCorrelator=[w]\nResponseCorelator=[w]\nDestination=[n2]\nSource=[n2]\n" }, { "Status Response", NULL, NULL }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Terminate Trace", NULL, NULL }, { "Data Ack", NULL, "[P3]TransmitCorrelator=[w][P2]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Data First/Middle", NULL, "Flags=[{RECEIVE_CONTINUE|NO_ACK||PIGGYBACK_ACK_INCLUDED|}]\nResyncIndicator=[w][P2]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Data Only/Last", NULL, "Flags=[{|NO_ACK|PIGGYBACK_ACK_ALLOWED|PIGGYBACK_ACK_INCLUDED|}]\nResyncIndicator=[w][P2]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Session Confirm", NULL, "Data1=[B]\nData2=[w]\nTransmitCorrelator=[w]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Session End", NULL, "[P1]Data2=[w][P4]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Session Initialize", NULL, "Data1=[B]\nData2=[w]\nTransmitCorrelator=[w]\nResponseCorelator=[w]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "No Receive", NULL, "Flags=[{|SEND_NO_ACK}]\nDataBytesAccepted=[b][P4]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Receive Outstanding", NULL, "[P1]DataBytesAccepted=[b][P4]\nRemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { "Receive Continue", NULL, "[P2]TransmitCorrelator=[w]\n[P2]RemoteSessionNumber=[B]\nLocalSessionNumber=[B]\n" }, { NULL, NULL, NULL }, /* not used */ { NULL, NULL, NULL }, /* not used */ { "Session Alive", NULL, NULL } }; void netbeui_print(netdissect_options *ndo, u_short control, const u_char *data, int length) { const u_char *maxbuf = data + length; int len; int command; const u_char *data2; int is_truncated = 0; if (maxbuf > ndo->ndo_snapend) maxbuf = ndo->ndo_snapend; ND_TCHECK(data[4]); len = EXTRACT_LE_16BITS(data); command = data[4]; data2 = data + len; if (data2 >= maxbuf) { data2 = maxbuf; is_truncated = 1; } startbuf = data; if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, "NBF Packet: ")); data = smb_fdata(ndo, data, "[P5]#", maxbuf, 0); } else { ND_PRINT((ndo, "\n>>> NBF Packet\nType=0x%X ", control)); data = smb_fdata(ndo, data, "Length=[d] Signature=[w] Command=[B]\n#", maxbuf, 0); } if (data == NULL) goto out; if (command > 0x1f || nbf_strings[command].name == NULL) { if (ndo->ndo_vflag < 2) data = smb_fdata(ndo, data, "Unknown NBF Command#", data2, 0); else data = smb_fdata(ndo, data, "Unknown NBF Command\n", data2, 0); } else { if (ndo->ndo_vflag < 2) { ND_PRINT((ndo, "%s", nbf_strings[command].name)); if (nbf_strings[command].nonverbose != NULL) data = smb_fdata(ndo, data, nbf_strings[command].nonverbose, data2, 0); } else { ND_PRINT((ndo, "%s:\n", nbf_strings[command].name)); if (nbf_strings[command].verbose != NULL) data = smb_fdata(ndo, data, nbf_strings[command].verbose, data2, 0); else ND_PRINT((ndo, "\n")); } } if (ndo->ndo_vflag < 2) return; if (data == NULL) goto out; if (is_truncated) { /* data2 was past the end of the buffer */ goto out; } /* If this isn't a command that would contain an SMB message, quit. */ if (command != 0x08 && command != 0x09 && command != 0x15 && command != 0x16) goto out; /* If there isn't enough data for "\377SMB", don't look for it. */ if (&data2[3] >= maxbuf) goto out; if (memcmp(data2, "\377SMB",4) == 0) print_smb(ndo, data2, maxbuf); else { int i; for (i = 0; i < 128; i++) { if (&data2[i + 3] >= maxbuf) break; if (memcmp(&data2[i], "\377SMB", 4) == 0) { ND_PRINT((ndo, "found SMB packet at %d\n", i)); print_smb(ndo, &data2[i], maxbuf); break; } } } out: ND_PRINT((ndo, "\n")); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * print IPX-Netbios frames */ void ipx_netbios_print(netdissect_options *ndo, const u_char *data, u_int length) { /* * this is a hack till I work out how to parse the rest of the * NetBIOS-over-IPX stuff */ int i; const u_char *maxbuf; maxbuf = data + length; /* Don't go past the end of the captured data in the packet. */ if (maxbuf > ndo->ndo_snapend) maxbuf = ndo->ndo_snapend; startbuf = data; for (i = 0; i < 128; i++) { if (&data[i + 4] > maxbuf) break; if (memcmp(&data[i], "\377SMB", 4) == 0) { smb_fdata(ndo, data, "\n>>> IPX transport ", &data[i], 0); print_smb(ndo, &data[i], maxbuf); ND_PRINT((ndo, "\n")); break; } } if (i == 128) smb_fdata(ndo, data, "\n>>> Unknown IPX ", maxbuf, 0); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_353_0
crossvul-cpp_data_good_2443_0
/* * plistutil.c * Simple tool to convert a plist into different formats * * Copyright (c) 2009-2015 Martin Szulecki All Rights Reserved. * Copyright (c) 2008 Zach C. All Rights Reserved. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plist/plist.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #ifdef _MSC_VER #pragma warning(disable:4996) #endif typedef struct _options { char *in_file, *out_file; uint8_t debug, in_fmt, out_fmt; } options_t; static void print_usage(int argc, char *argv[]) { char *name = NULL; name = strrchr(argv[0], '/'); printf("Usage: %s -i|--infile FILE [-o|--outfile FILE] [-d|--debug]\n", (name ? name + 1: argv[0])); printf("Convert a plist FILE from binary to XML format or vice-versa.\n\n"); printf(" -i, --infile FILE\tThe FILE to convert from\n"); printf(" -o, --outfile FILE\tOptional FILE to convert to or stdout if not used\n"); printf(" -d, --debug\t\tEnable extended debug output\n"); printf("\n"); } static options_t *parse_arguments(int argc, char *argv[]) { int i = 0; options_t *options = (options_t *) malloc(sizeof(options_t)); memset(options, 0, sizeof(options_t)); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "--infile") || !strcmp(argv[i], "-i")) { if ((i + 1) == argc) { free(options); return NULL; } options->in_file = argv[i + 1]; i++; continue; } if (!strcmp(argv[i], "--outfile") || !strcmp(argv[i], "-o")) { if ((i + 1) == argc) { free(options); return NULL; } options->out_file = argv[i + 1]; i++; continue; } if (!strcmp(argv[i], "--debug") || !strcmp(argv[i], "-d")) { options->debug = 1; } if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { free(options); return NULL; } } if (!options->in_file) { free(options); return NULL; } return options; } int main(int argc, char *argv[]) { FILE *iplist = NULL; plist_t root_node = NULL; char *plist_out = NULL; uint32_t size = 0; int read_size = 0; char *plist_entire = NULL; struct stat filestats; options_t *options = parse_arguments(argc, argv); if (!options) { print_usage(argc, argv); return 0; } // read input file iplist = fopen(options->in_file, "rb"); if (!iplist) { free(options); return 1; } stat(options->in_file, &filestats); if (filestats.st_size < 8) { printf("ERROR: Input file is too small to contain valid plist data.\n"); return -1; } plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); fclose(iplist); // convert from binary to xml or vice-versa if (memcmp(plist_entire, "bplist00", 8) == 0) { plist_from_bin(plist_entire, read_size, &root_node); plist_to_xml(root_node, &plist_out, &size); } else { plist_from_xml(plist_entire, read_size, &root_node); plist_to_bin(root_node, &plist_out, &size); } plist_free(root_node); free(plist_entire); if (plist_out) { if (options->out_file != NULL) { FILE *oplist = fopen(options->out_file, "wb"); if (!oplist) { free(options); return 1; } fwrite(plist_out, size, sizeof(char), oplist); fclose(oplist); } // if no output file specified, write to stdout else fwrite(plist_out, size, sizeof(char), stdout); free(plist_out); } else printf("ERROR: Failed to convert input file.\n"); free(options); return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2443_0
crossvul-cpp_data_good_5241_1
/* TIFF - Tagged Image File Format Encapsulation for GD Library gd_tiff.c Copyright (C) Pierre-A. Joye, M. Retallack --------------------------------------------------------------------------- ** ** 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. This software is provided "as is" without express or ** implied warranty. ** --------------------------------------------------------------------------- Ctx code written by M. Retallack Todo: If we fail - cleanup Writer: Use gd error function, overflow check may not be necessary as we write our own data (check already done) Implement 2 color black/white saving using group4 fax compression Implement function to specify encoding to use when writing tiff data ---------------------------------------------------------------------------- */ /* $Id$ */ /** * File: TIFF IO * * Read and write TIFF images. * * There is only most basic support for the TIFF format available for now; * for instance, multiple pages are not yet supported. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "gd.h" #include "gd_errors.h" #include "gdfonts.h" #include <stdio.h> #include <stdlib.h> #include <limits.h> #include "gdhelpers.h" #ifdef HAVE_LIBTIFF #include "tiff.h" #include "tiffio.h" #define GD_SUCCESS 1 #define GD_FAILURE 0 #define TRUE 1 #define FALSE 0 /* I define those here until the new formats * are commited. We can then rely on the global * def */ #define GD_PALETTE 1 #define GD_TRUECOLOR 2 #define GD_GRAY 3 #define GD_INDEXED 4 #define GD_RGB 5 #define MIN(a,b) (a < b) ? a : b; #define MAX(a,b) (a > b) ? a : b; typedef struct tiff_handle { int size; int pos; gdIOCtx *ctx; int written; } tiff_handle; /* Functions for reading, writing and seeking in gdIOCtx This allows for non-file i/o operations with no explicit use of libtiff fileio wrapper functions Note: because libtiff requires random access, but gdIOCtx only supports streams, all writes are buffered into memory and written out on close, also all reads are done from a memory mapped version of the tiff (assuming one already exists) */ tiff_handle * new_tiff_handle(gdIOCtx *g) { tiff_handle * t; if (!g) { gd_error("Cannot create a new tiff handle, missing Ctx argument"); return NULL; } t = (tiff_handle *) gdMalloc(sizeof(tiff_handle)); if (!t) { gd_error("Failed to allocate a new tiff handle"); return NULL; } t->size = 0; t->pos = 0; t->ctx = g; t->written = 0; return t; } /* TIFFReadWriteProc tiff_readproc - Will use gdIOCtx procs to read required (previously written) TIFF file content */ static tsize_t tiff_readproc(thandle_t clientdata, tdata_t data, tsize_t size) { tiff_handle *th = (tiff_handle *)clientdata; gdIOCtx *ctx = th->ctx; size = (ctx->getBuf)(ctx, data, size); return size; } /* TIFFReadWriteProc tiff_writeproc - Will use gdIOCtx procs to write out TIFF data */ static tsize_t tiff_writeproc(thandle_t clientdata, tdata_t data, tsize_t size) { tiff_handle *th = (tiff_handle *)clientdata; gdIOCtx *ctx = th->ctx; size = (ctx->putBuf)(ctx, data, size); if(size + th->pos>th->size) { th->size = size + th->pos; th->pos += size; } return size; } /* TIFFSeekProc tiff_seekproc * used to move around the partially written TIFF */ static toff_t tiff_seekproc(thandle_t clientdata, toff_t offset, int from) { tiff_handle *th = (tiff_handle *)clientdata; gdIOCtx *ctx = th->ctx; int result; switch(from) { default: case SEEK_SET: /* just use offset */ break; case SEEK_END: /* invert offset, so that it is from start, not end as supplied */ offset = th->size + offset; break; case SEEK_CUR: /* add current position to translate it to 'from start', * not from durrent as supplied */ offset += th->pos; break; } /* now, move pos in both io context and buf */ if((result = (ctx->seek)(ctx, offset))) { th->pos = offset; } return result ? offset : (toff_t)-1; } /* TIFFCloseProc tiff_closeproc - used to finally close the TIFF file */ static int tiff_closeproc(thandle_t clientdata) { (void)clientdata; /*tiff_handle *th = (tiff_handle *)clientdata; gdIOCtx *ctx = th->ctx; (ctx->gd_free)(ctx);*/ return 0; } /* TIFFSizeProc tiff_sizeproc */ static toff_t tiff_sizeproc(thandle_t clientdata) { tiff_handle *th = (tiff_handle *)clientdata; return th->size; } /* TIFFMapFileProc tiff_mapproc() */ static int tiff_mapproc(thandle_t h, tdata_t *d, toff_t *o) { (void)h; (void)d; (void)o; return 0; } /* TIFFUnmapFileProc tiff_unmapproc */ static void tiff_unmapproc(thandle_t h, tdata_t d, toff_t o) { (void)h; (void)d; (void)o; } /* tiffWriter * ---------- * Write the gd image as a tiff file (called by gdImageTiffCtx) * Parameters are: * image: gd image structure; * out: the stream where to write * bitDepth: depth in bits of each pixel */ void tiffWriter(gdImagePtr image, gdIOCtx *out, int bitDepth) { int x, y; int i; int r, g, b, a; TIFF *tiff; int width, height; int color; char *scan; int samplesPerPixel = 3; int bitsPerSample; int transparentColorR = -1; int transparentColorG = -1; int transparentColorB = -1; uint16 extraSamples[1]; uint16 *colorMapRed = NULL; uint16 *colorMapGreen = NULL; uint16 *colorMapBlue = NULL; tiff_handle *th; th = new_tiff_handle(out); if (!th) { return; } extraSamples[0] = EXTRASAMPLE_ASSOCALPHA; /* read in the width/height of gd image */ width = gdImageSX(image); height = gdImageSY(image); /* reset clip region to whole image */ gdImageSetClip(image, 0, 0, width, height); /* handle old-style single-colour mapping to 100% transparency */ if(image->transparent != -1) { /* set our 100% transparent colour value */ transparentColorR = gdImageRed(image, image->transparent); transparentColorG = gdImageGreen(image, image->transparent); transparentColorB = gdImageBlue(image, image->transparent); } /* Open tiff file writing routines, but use special read/write/seek * functions so that tiff lib writes correct bits of tiff content to * correct areas of file opened and modifieable by the gdIOCtx functions */ tiff = TIFFClientOpen("", "w", th, tiff_readproc, tiff_writeproc, tiff_seekproc, tiff_closeproc, tiff_sizeproc, tiff_mapproc, tiff_unmapproc); TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height); TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, (bitDepth == 24) ? PHOTOMETRIC_RGB : PHOTOMETRIC_PALETTE); bitsPerSample = (bitDepth == 24 || bitDepth == 8) ? 8 : 1; TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, bitsPerSample); TIFFSetField(tiff, TIFFTAG_XRESOLUTION, (float)image->res_x); TIFFSetField(tiff, TIFFTAG_YRESOLUTION, (float)image->res_y); /* build the color map for 8 bit images */ if(bitDepth != 24) { colorMapRed = (uint16 *) gdMalloc(3 * (1 << bitsPerSample)); if (!colorMapRed) { gdFree(th); return; } colorMapGreen = (uint16 *) gdMalloc(3 * (1 << bitsPerSample)); if (!colorMapGreen) { gdFree(colorMapRed); gdFree(th); return; } colorMapBlue = (uint16 *) gdMalloc(3 * (1 << bitsPerSample)); if (!colorMapBlue) { gdFree(colorMapRed); gdFree(colorMapGreen); gdFree(th); return; } for(i = 0; i < image->colorsTotal; i++) { colorMapRed[i] = gdImageRed(image,i) + (gdImageRed(image,i) * 256); colorMapGreen[i] = gdImageGreen(image,i)+(gdImageGreen(image,i)*256); colorMapBlue[i] = gdImageBlue(image,i) + (gdImageBlue(image,i)*256); } TIFFSetField(tiff, TIFFTAG_COLORMAP, colorMapRed, colorMapGreen, colorMapBlue); samplesPerPixel = 1; } /* here, we check if the 'save alpha' flag is set on the source gd image */ if ((bitDepth == 24) && (image->saveAlphaFlag || image->transparent != -1)) { /* so, we need to store the alpha values too! * Also, tell TIFF what the extra sample means (associated alpha) */ samplesPerPixel = 4; TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel); TIFFSetField(tiff, TIFFTAG_EXTRASAMPLES, 1, extraSamples); } else { TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel); } TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, 1); if(overflow2(width, samplesPerPixel)) { if (colorMapRed) gdFree(colorMapRed); if (colorMapGreen) gdFree(colorMapGreen); if (colorMapBlue) gdFree(colorMapBlue); gdFree(th); return; } if(!(scan = (char *)gdMalloc(width * samplesPerPixel))) { if (colorMapRed) gdFree(colorMapRed); if (colorMapGreen) gdFree(colorMapGreen); if (colorMapBlue) gdFree(colorMapBlue); gdFree(th); return; } /* loop through y-coords, and x-coords */ for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* generate scan line for writing to tiff */ color = gdImageGetPixel(image, x, y); a = (127 - gdImageAlpha(image, color)) * 2; a = (a == 0xfe) ? 0xff : a & 0xff; b = gdImageBlue(image, color); g = gdImageGreen(image, color); r = gdImageRed(image, color); /* if this pixel has the same RGB as the transparent colour, * then set alpha fully transparent */ if (transparentColorR == r && transparentColorG == g && transparentColorB == b) { a = 0x00; } if(bitDepth != 24) { /* write out 1 or 8 bit value in 1 byte * (currently treats 1bit as 8bit) */ scan[(x * samplesPerPixel) + 0] = color; } else { /* write out 24 bit value in 3 (or 4 if transparent) bytes */ if(image->saveAlphaFlag || image->transparent != -1) { scan[(x * samplesPerPixel) + 3] = a; } scan[(x * samplesPerPixel) + 2] = b; scan[(x * samplesPerPixel) + 1] = g; scan[(x * samplesPerPixel) + 0] = r; } } /* Write the scan line to the tiff */ if(TIFFWriteEncodedStrip(tiff, y, scan, width * samplesPerPixel) == -1) { if (colorMapRed) gdFree(colorMapRed); if (colorMapGreen) gdFree(colorMapGreen); if (colorMapBlue) gdFree(colorMapBlue); gdFree(th); /* error handler here */ gd_error("Could not create TIFF\n"); return; } } /* now cloase and free up resources */ TIFFClose(tiff); gdFree(scan); gdFree(th); if(bitDepth != 24) { gdFree(colorMapRed); gdFree(colorMapGreen); gdFree(colorMapBlue); } } /* Function: gdImageTiffCtx Write the gd image as a tiff file. Parameters: image - gd image structure; out - the stream where to write */ BGD_DECLARE(void) gdImageTiffCtx(gdImagePtr image, gdIOCtx *out) { int clipx1P, clipy1P, clipx2P, clipy2P; int bitDepth = 24; /* First, switch off clipping, or we'll not get all the image! */ gdImageGetClip(image, &clipx1P, &clipy1P, &clipx2P, &clipy2P); /* use the appropriate routine depending on the bit depth of the image */ if(image->trueColor) { bitDepth = 24; } else if(image->colorsTotal == 2) { bitDepth = 1; } else { bitDepth = 8; } tiffWriter(image, out, bitDepth); /* reset clipping area to the gd image's original values */ gdImageSetClip(image, clipx1P, clipy1P, clipx2P, clipy2P); } /* Check if we are really in 8bit mode */ static int checkColorMap(n, r, g, b) int n; uint16 *r, *g, *b; { while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); return (8); } /* Read and convert a TIFF colormap */ static int readTiffColorMap(gdImagePtr im, TIFF *tif, char is_bw, int photometric) { uint16 *redcmap, *greencmap, *bluecmap; uint16 bps; int i; if (is_bw) { if (photometric == PHOTOMETRIC_MINISWHITE) { gdImageColorAllocate(im, 255,255,255); gdImageColorAllocate(im, 0, 0, 0); } else { gdImageColorAllocate(im, 0, 0, 0); gdImageColorAllocate(im, 255,255,255); } } else { uint16 min_sample_val, max_sample_val; if (!TIFFGetField(tif, TIFFTAG_MINSAMPLEVALUE, &min_sample_val)) { min_sample_val = 0; } if (!TIFFGetField(tif, TIFFTAG_MAXSAMPLEVALUE, &max_sample_val)) { max_sample_val = 255; } if (photometric == PHOTOMETRIC_MINISBLACK || photometric == PHOTOMETRIC_MINISWHITE) { /* TODO: use TIFFTAG_MINSAMPLEVALUE and TIFFTAG_MAXSAMPLEVALUE */ /* Gray level palette */ for (i=min_sample_val; i <= max_sample_val; i++) { gdImageColorAllocate(im, i,i,i); } return GD_SUCCESS; } else if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &redcmap, &greencmap, &bluecmap)) { gd_error("Cannot read the color map"); return GD_FAILURE; } TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps); #define CVT(x) (((x) * 255) / ((1L<<16)-1)) if (checkColorMap(1<<bps, redcmap, greencmap, bluecmap) == 16) { for (i = (1<<bps)-1; i > 0; i--) { redcmap[i] = CVT(redcmap[i]); greencmap[i] = CVT(greencmap[i]); bluecmap[i] = CVT(bluecmap[i]); } } for (i = 0; i < 256; i++) { gdImageColorAllocate(im, redcmap[i], greencmap[i], bluecmap[i]); } #undef CVT } return GD_SUCCESS; } static void readTiffBw (const unsigned char *src, gdImagePtr im, uint16 photometric, int startx, int starty, int width, int height, char has_alpha, int extra, int align) { int x = startx, y = starty; (void)has_alpha; (void)extra; (void)align; for (y = starty; y < starty + height; y++) { for (x = startx; x < startx + width; x++) { register unsigned char curr = *src++; register unsigned char mask; if (photometric == PHOTOMETRIC_MINISWHITE) { curr = ~curr; } for (mask = 0x80; mask != 0 && x < startx + width; mask >>= 1) { gdImageSetPixel(im, x, y, ((curr & mask) != 0)?0:1); } } } } static void readTiff8bit (const unsigned char *src, gdImagePtr im, uint16 photometric, int startx, int starty, int width, int height, char has_alpha, int extra, int align) { int red, green, blue, alpha; int x, y; (void)extra; (void)align; switch (photometric) { case PHOTOMETRIC_PALETTE: /* Palette has no alpha (see TIFF specs for more details */ for (y = starty; y < starty + height; y++) { for (x = startx; x < startx + width; x++) { gdImageSetPixel(im, x, y,*(src++)); } } break; case PHOTOMETRIC_RGB: if (has_alpha) { gdImageAlphaBlending(im, 0); gdImageSaveAlpha(im, 1); for (y = starty; y < starty + height; y++) { for (x = startx; x < startx + width; x++) { red = *src++; green = *src++; blue = *src++; alpha = *src++; red = MIN (red, alpha); blue = MIN (blue, alpha); green = MIN (green, alpha); if (alpha) { gdImageSetPixel(im, x, y, gdTrueColorAlpha(red * 255 / alpha, green * 255 / alpha, blue * 255 /alpha, gdAlphaMax - (alpha >> 1))); } else { gdImageSetPixel(im, x, y, gdTrueColorAlpha(red, green, blue, gdAlphaMax - (alpha >> 1))); } } } } else { for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { register unsigned char r = *src++; register unsigned char g = *src++; register unsigned char b = *src++; gdImageSetPixel(im, x, y, gdTrueColor(r, g, b)); } } } break; case PHOTOMETRIC_MINISWHITE: if (has_alpha) { /* We don't process the extra yet */ } else { for (y = starty; y < starty + height; y++) { for (x = startx; x < startx + width; x++) { gdImageSetPixel(im, x, y, ~(*src++)); } } } break; case PHOTOMETRIC_MINISBLACK: if (has_alpha) { /* We don't process the extra yet */ } else { for (y = starty; y < height; y++) { for (x = 0; x < width; x++) { gdImageSetPixel(im, x, y, *src++); } } } break; } } static int createFromTiffTiles(TIFF *tif, gdImagePtr im, uint16 bps, uint16 photometric, char has_alpha, char is_bw, int extra) { uint16 planar; int im_width, im_height; int tile_width, tile_height; int x, y, height, width; unsigned char *buffer; if (!TIFFGetField (tif, TIFFTAG_PLANARCONFIG, &planar)) { planar = PLANARCONFIG_CONTIG; } if (TIFFGetField (tif, TIFFTAG_IMAGEWIDTH, &im_width) == 0 || TIFFGetField (tif, TIFFTAG_IMAGELENGTH, &im_height) == 0 || TIFFGetField (tif, TIFFTAG_TILEWIDTH, &tile_width) == 0 || TIFFGetField (tif, TIFFTAG_TILELENGTH, &tile_height) == 0) { return FALSE; } buffer = (unsigned char *) gdMalloc (TIFFTileSize (tif)); if (!buffer) { return FALSE; } for (y = 0; y < im_height; y += tile_height) { for (x = 0; x < im_width; x += tile_width) { TIFFReadTile(tif, buffer, x, y, 0, 0); width = MIN(im_width - x, tile_width); height = MIN(im_height - y, tile_height); if (bps == 16) { } else if (bps == 8) { readTiff8bit(buffer, im, photometric, x, y, width, height, has_alpha, extra, 0); } else if (is_bw) { readTiffBw(buffer, im, photometric, x, y, width, height, has_alpha, extra, 0); } else { /* TODO: implement some default reader or detect this case earlier use force_rgb */ } } } gdFree(buffer); return TRUE; } static int createFromTiffLines(TIFF *tif, gdImagePtr im, uint16 bps, uint16 photometric, char has_alpha, char is_bw, int extra) { uint16 planar; uint32 im_height, im_width, y; unsigned char *buffer; if (!TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar)) { planar = PLANARCONFIG_CONTIG; } if (!TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &im_height)) { gd_error("Can't fetch TIFF height\n"); return FALSE; } if (!TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &im_width)) { gd_error("Can't fetch TIFF width \n"); return FALSE; } buffer = (unsigned char *)gdMalloc(im_width * 4); if (!buffer) { return GD_FAILURE; } if (planar == PLANARCONFIG_CONTIG) { switch (bps) { case 16: /* TODO * or simply use force_rgba */ break; case 8: for (y = 0; y < im_height; y++ ) { if (!TIFFReadScanline (tif, buffer, y, 0)) { gd_error("Error while reading scanline %i", y); break; } /* reading one line at a time */ readTiff8bit(buffer, im, photometric, 0, y, im_width, 1, has_alpha, extra, 0); } break; default: if (is_bw) { for (y = 0; y < im_height; y++ ) { if (!TIFFReadScanline (tif, buffer, y, 0)) { gd_error("Error while reading scanline %i", y); break; } /* reading one line at a time */ readTiffBw(buffer, im, photometric, 0, y, im_width, 1, has_alpha, extra, 0); } } else { /* TODO: implement some default reader or detect this case earlier > force_rgb */ } break; } } else { /* TODO: implement a reader for separate panes. We detect this case earlier for now and use force_rgb */ } gdFree(buffer); return GD_SUCCESS; } static int createFromTiffRgba(TIFF * tif, gdImagePtr im) { int a; int x, y; int alphaBlendingFlag = 0; int color; int width = im->sx; int height = im->sy; uint32 *buffer; uint32 rgba; int success; /* switch off colour merging on target gd image just while we write out * content - we want to preserve the alpha data until the user chooses * what to do with the image */ alphaBlendingFlag = im->alphaBlendingFlag; gdImageAlphaBlending(im, 0); buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height); if (!buffer) { return GD_FAILURE; } success = TIFFReadRGBAImage(tif, width, height, buffer, 1); if (success) { for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* if it doesn't already exist, allocate a new colour, * else use existing one */ rgba = buffer[(y * width + x)]; a = (0xff - TIFFGetA(rgba)) / 2; color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a); /* set pixel colour to this colour */ gdImageSetPixel(im, x, height - y - 1, color); } } } gdFree(buffer); /* now reset colour merge for alpha blending routines */ gdImageAlphaBlending(im, alphaBlendingFlag); return success; } /* Function: gdImageCreateFromTiffCtx Create a gdImage from a TIFF file input from an gdIOCtx. */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTiffCtx(gdIOCtx *infile) { TIFF *tif; tiff_handle *th; uint16 bps, spp, photometric; uint16 orientation; int width, height; uint16 extra, *extra_types; uint16 planar; char has_alpha, is_bw, is_gray; char force_rgba = FALSE; char save_transparent; int image_type; int ret; float res_float; gdImagePtr im = NULL; th = new_tiff_handle(infile); if (!th) { return NULL; } tif = TIFFClientOpen("", "rb", th, tiff_readproc, tiff_writeproc, tiff_seekproc, tiff_closeproc, tiff_sizeproc, tiff_mapproc, tiff_unmapproc); if (!tif) { gd_error("Cannot open TIFF image"); gdFree(th); return NULL; } if (!TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width)) { gd_error("TIFF error, Cannot read image width"); goto error; } if (!TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height)) { gd_error("TIFF error, Cannot read image width"); goto error; } TIFFGetFieldDefaulted (tif, TIFFTAG_BITSPERSAMPLE, &bps); /* Unsupported bps, force to RGBA */ if (1/*bps > 8 && bps != 16*/) { force_rgba = TRUE; } TIFFGetFieldDefaulted (tif, TIFFTAG_SAMPLESPERPIXEL, &spp); if (!TIFFGetField (tif, TIFFTAG_EXTRASAMPLES, &extra, &extra_types)) { extra = 0; } if (!TIFFGetField (tif, TIFFTAG_PHOTOMETRIC, &photometric)) { uint16 compression; if (TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression) && (compression == COMPRESSION_CCITTFAX3 || compression == COMPRESSION_CCITTFAX4 || compression == COMPRESSION_CCITTRLE || compression == COMPRESSION_CCITTRLEW)) { gd_error("Could not get photometric. " "Image is CCITT compressed, assuming min-is-white"); photometric = PHOTOMETRIC_MINISWHITE; } else { gd_error("Could not get photometric. " "Assuming min-is-black"); photometric = PHOTOMETRIC_MINISBLACK; } } save_transparent = FALSE; /* test if the extrasample represents an associated alpha channel... */ if (extra > 0 && (extra_types[0] == EXTRASAMPLE_ASSOCALPHA)) { has_alpha = TRUE; save_transparent = FALSE; --extra; } else if (extra > 0 && (extra_types[0] == EXTRASAMPLE_UNASSALPHA)) { has_alpha = TRUE; save_transparent = TRUE; --extra; } else if (extra > 0 && (extra_types[0] == EXTRASAMPLE_UNSPECIFIED)) { /* assuming unassociated alpha if unspecified */ gd_error("alpha channel type not defined, assuming alpha is not premultiplied"); has_alpha = TRUE; save_transparent = TRUE; --extra; } else { has_alpha = FALSE; } if (photometric == PHOTOMETRIC_RGB && spp > 3 + extra) { has_alpha = TRUE; extra = spp - 4; } else if (photometric != PHOTOMETRIC_RGB && spp > 1 + extra) { has_alpha = TRUE; extra = spp - 2; } is_bw = FALSE; is_gray = FALSE; switch (photometric) { case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_MINISWHITE: if (!has_alpha && bps == 1 && spp == 1) { image_type = GD_INDEXED; is_bw = TRUE; } else { image_type = GD_GRAY; } break; case PHOTOMETRIC_RGB: image_type = GD_RGB; break; case PHOTOMETRIC_PALETTE: image_type = GD_INDEXED; break; default: force_rgba = TRUE; break; } if (!TIFFGetField (tif, TIFFTAG_PLANARCONFIG, &planar)) { planar = PLANARCONFIG_CONTIG; } /* Force rgba if image plans are not contiguous */ if (force_rgba || planar != PLANARCONFIG_CONTIG) { image_type = GD_RGB; } if (!force_rgba && (image_type == GD_PALETTE || image_type == GD_INDEXED || image_type == GD_GRAY)) { im = gdImageCreate(width, height); if (!im) goto error; readTiffColorMap(im, tif, is_bw, photometric); } else { im = gdImageCreateTrueColor(width, height); if (!im) goto error; } #ifdef DEBUG printf("force rgba: %i\n", force_rgba); printf("has_alpha: %i\n", has_alpha); printf("save trans: %i\n", save_transparent); printf("is_bw: %i\n", is_bw); printf("is_gray: %i\n", is_gray); printf("type: %i\n", image_type); #else (void)is_gray; (void)save_transparent; #endif if (force_rgba) { ret = createFromTiffRgba(tif, im); } else if (TIFFIsTiled(tif)) { ret = createFromTiffTiles(tif, im, bps, photometric, has_alpha, is_bw, extra); } else { ret = createFromTiffLines(tif, im, bps, photometric, has_alpha, is_bw, extra); } if (!ret) { gdImageDestroy(im); im = NULL; goto error; } if (TIFFGetField(tif, TIFFTAG_XRESOLUTION, &res_float)) { im->res_x = (unsigned int)res_float; //truncate } if (TIFFGetField(tif, TIFFTAG_YRESOLUTION, &res_float)) { im->res_y = (unsigned int)res_float; //truncate } if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) { switch (orientation) { case ORIENTATION_TOPLEFT: case ORIENTATION_TOPRIGHT: case ORIENTATION_BOTRIGHT: case ORIENTATION_BOTLEFT: break; default: gd_error("Orientation %d not handled yet!", orientation); break; } } error: TIFFClose(tif); gdFree(th); return im; } /* Function: gdImageCreateFromTIFF */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTiff(FILE *inFile) { gdImagePtr im; gdIOCtx *in = gdNewFileCtx(inFile); if (in == NULL) return NULL; im = gdImageCreateFromTiffCtx(in); in->gd_free(in); return im; } /* Function: gdImageCreateFromTiffPtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTiffPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTiffCtx(in); in->gd_free(in); return im; } /* Function: gdImageTiff */ BGD_DECLARE(void) gdImageTiff(gdImagePtr im, FILE *outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) return; gdImageTiffCtx(im, out); /* what's an fg again? */ out->gd_free(out); } /* Function: gdImageTiffPtr */ BGD_DECLARE(void *) gdImageTiffPtr(gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); if (out == NULL) return NULL; gdImageTiffCtx(im, out); /* what's an fg again? */ rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_5241_1
crossvul-cpp_data_good_1984_1
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * JP2 Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include "jp2_dec.h" #include "jp2_cod.h" #include "jasper/jas_image.h" #include "jasper/jas_stream.h" #include "jasper/jas_math.h" #include "jasper/jas_debug.h" #include "jasper/jas_malloc.h" #include "jasper/jas_types.h" #include <assert.h> #include <stdio.h> #define JP2_VALIDATELEN (JAS_MIN(JP2_JP_LEN + 16, JAS_STREAM_MAXPUTBACK)) static jp2_dec_t *jp2_dec_create(void); static void jp2_dec_destroy(jp2_dec_t *dec); static int jp2_getcs(jp2_colr_t *colr); static int fromiccpcs(int cs); static int jp2_getct(int colorspace, int type, int assoc); /******************************************************************************\ * Functions. \******************************************************************************/ jas_image_t *jp2_decode(jas_stream_t *in, const char *optstr) { jp2_box_t *box; int found; jas_image_t *image; jp2_dec_t *dec; bool samedtype; int dtype; unsigned int i; jp2_cmap_t *cmapd; jp2_pclr_t *pclrd; jp2_cdef_t *cdefd; unsigned int channo; int newcmptno; int_fast32_t *lutents; #if 0 jp2_cdefchan_t *cdefent; int cmptno; #endif jp2_cmapent_t *cmapent; jas_icchdr_t icchdr; jas_iccprof_t *iccprof; dec = 0; box = 0; image = 0; JAS_DBGLOG(100, ("jp2_decode(%p, \"%s\")\n", in, optstr)); if (!(dec = jp2_dec_create())) { goto error; } /* Get the first box. This should be a JP box. */ if (!(box = jp2_box_get(in))) { jas_eprintf("error: cannot get box\n"); goto error; } if (box->type != JP2_BOX_JP) { jas_eprintf("error: expecting signature box\n"); goto error; } if (box->data.jp.magic != JP2_JP_MAGIC) { jas_eprintf("incorrect magic number\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get the second box. This should be a FTYP box. */ if (!(box = jp2_box_get(in))) { goto error; } if (box->type != JP2_BOX_FTYP) { jas_eprintf("expecting file type box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get more boxes... */ found = 0; while ((box = jp2_box_get(in))) { if (jas_getdbglevel() >= 1) { jas_eprintf("got box type %s\n", box->info->name); } switch (box->type) { case JP2_BOX_JP2C: found = 1; break; case JP2_BOX_IHDR: if (!dec->ihdr) { dec->ihdr = box; box = 0; } break; case JP2_BOX_BPCC: if (!dec->bpcc) { dec->bpcc = box; box = 0; } break; case JP2_BOX_CDEF: if (!dec->cdef) { dec->cdef = box; box = 0; } break; case JP2_BOX_PCLR: if (!dec->pclr) { dec->pclr = box; box = 0; } break; case JP2_BOX_CMAP: if (!dec->cmap) { dec->cmap = box; box = 0; } break; case JP2_BOX_COLR: if (!dec->colr) { dec->colr = box; box = 0; } break; } if (box) { jp2_box_destroy(box); box = 0; } if (found) { break; } } if (!found) { jas_eprintf("error: no code stream found\n"); goto error; } if (!(dec->image = jpc_decode(in, optstr))) { jas_eprintf("error: cannot decode code stream\n"); goto error; } /* An IHDR box must be present. */ if (!dec->ihdr) { jas_eprintf("error: missing IHDR box\n"); goto error; } /* Does the number of components indicated in the IHDR box match the value specified in the code stream? */ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: number of components mismatch (IHDR)\n"); goto error; } /* At least one component must be present. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } /* Determine if all components have the same data type. */ samedtype = true; dtype = jas_image_cmptdtype(dec->image, 0); for (i = 1; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != dtype) { samedtype = false; break; } } /* Is the component data type indicated in the IHDR box consistent with the data in the code stream? */ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { jas_eprintf("error: component data type mismatch (IHDR)\n"); goto error; } /* Is the compression type supported? */ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { jas_eprintf("error: unsupported compression type\n"); goto error; } if (dec->bpcc) { /* Is the number of components indicated in the BPCC box consistent with the code stream data? */ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: number of components mismatch (BPCC)\n"); goto error; } /* Is the component data type information indicated in the BPCC box consistent with the code stream data? */ if (!samedtype) { for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { jas_eprintf("error: component data type mismatch (BPCC)\n"); goto error; } } } else { jas_eprintf("warning: superfluous BPCC box\n"); } } /* A COLR box must be present. */ if (!dec->colr) { jas_eprintf("error: no COLR box\n"); goto error; } switch (dec->colr->data.colr.method) { case JP2_COLR_ENUM: jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); break; case JP2_COLR_ICC: iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, dec->colr->data.colr.iccplen); if (!iccprof) { jas_eprintf("error: failed to parse ICC profile\n"); goto error; } jas_iccprof_gethdr(iccprof, &icchdr); jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc); jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); if (!dec->image->cmprof_) { jas_iccprof_destroy(iccprof); goto error; } jas_iccprof_destroy(iccprof); break; } /* If a CMAP box is present, a PCLR box must also be present. */ if (dec->cmap && !dec->pclr) { jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n"); jp2_box_destroy(dec->cmap); dec->cmap = 0; } /* If a CMAP box is not present, a PCLR box must not be present. */ if (!dec->cmap && dec->pclr) { jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n"); jp2_box_destroy(dec->pclr); dec->pclr = 0; } /* Determine the number of channels (which is essentially the number of components after any palette mappings have been applied). */ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); /* Perform a basic sanity check on the CMAP box if present. */ if (dec->cmap) { for (i = 0; i < dec->numchans; ++i) { /* Is the component number reasonable? */ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(jas_uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: invalid component number in CMAP box\n"); goto error; } /* Is the LUT index reasonable? */ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { jas_eprintf("error: invalid CMAP LUT index\n"); goto error; } } } /* Allocate space for the channel-number to component-number LUT. */ if (!(dec->chantocmptlut = jas_alloc2(dec->numchans, sizeof(uint_fast16_t)))) { jas_eprintf("error: no memory\n"); goto error; } if (!dec->cmap) { for (i = 0; i < dec->numchans; ++i) { dec->chantocmptlut[i] = i; } } else { cmapd = &dec->cmap->data.cmap; pclrd = &dec->pclr->data.pclr; cdefd = &dec->cdef->data.cdef; for (channo = 0; channo < cmapd->numchans; ++channo) { cmapent = &cmapd->ents[channo]; if (cmapent->map == JP2_CMAP_DIRECT) { dec->chantocmptlut[channo] = channo; } else if (cmapent->map == JP2_CMAP_PALETTE) { if (!pclrd->numlutents) { goto error; } lutents = jas_alloc2(pclrd->numlutents, sizeof(int_fast32_t)); if (!lutents) { goto error; } for (i = 0; i < pclrd->numlutents; ++i) { lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; } newcmptno = jas_image_numcmpts(dec->image); jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); dec->chantocmptlut[channo] = newcmptno; jas_free(lutents); #if 0 if (dec->cdef) { cdefent = jp2_cdef_lookup(cdefd, channo); if (!cdefent) { abort(); } jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); } else { jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); } #else /* suppress -Wunused-but-set-variable */ (void)cdefd; #endif } else { jas_eprintf("error: invalid MTYP in CMAP box\n"); goto error; } } } /* Ensure that the number of channels being used by the decoder matches the number of image components. */ if (dec->numchans != jas_image_numcmpts(dec->image)) { jas_eprintf("error: mismatch in number of components (%d != %d)\n", dec->numchans, jas_image_numcmpts(dec->image)); goto error; } /* Mark all components as being of unknown type. */ for (i = 0; i < JAS_CAST(jas_uint, jas_image_numcmpts(dec->image)); ++i) { jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); } /* Determine the type of each component. */ if (dec->cdef) { for (i = 0; i < dec->cdef->data.cdef.numchans; ++i) { /* Is the channel number reasonable? */ if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { jas_eprintf("error: invalid channel number in CDEF box\n"); goto error; } jas_image_setcmpttype(dec->image, dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], jp2_getct(jas_image_clrspc(dec->image), dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); } } else { for (i = 0; i < dec->numchans; ++i) { jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); } } /* Delete any components that are not of interest. */ for (i = jas_image_numcmpts(dec->image); i > 0; --i) { if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { jas_image_delcmpt(dec->image, i - 1); } } /* Ensure that some components survived. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } #if 0 jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image)); #endif /* Prevent the image from being destroyed later. */ image = dec->image; dec->image = 0; jp2_dec_destroy(dec); return image; error: if (box) { jp2_box_destroy(box); } if (dec) { jp2_dec_destroy(dec); } return 0; } int jp2_validate(jas_stream_t *in) { unsigned char buf[JP2_VALIDATELEN]; #if 0 jas_stream_t *tmpstream; jp2_box_t *box; #endif assert(JAS_STREAM_MAXPUTBACK >= JP2_VALIDATELEN); /* Read the validation data (i.e., the data used for detecting the format). */ if (jas_stream_peek(in, buf, sizeof(buf)) != sizeof(buf)) return -1; /* Is the box type correct? */ if ((((uint_least32_t)buf[4] << 24) | ((uint_least32_t)buf[5] << 16) | ((uint_least32_t)buf[6] << 8) | (uint_least32_t)buf[7]) != JP2_BOX_JP) { return -1; } return 0; } static jp2_dec_t *jp2_dec_create(void) { jp2_dec_t *dec; if (!(dec = jas_malloc(sizeof(jp2_dec_t)))) { return 0; } dec->ihdr = 0; dec->bpcc = 0; dec->cdef = 0; dec->pclr = 0; dec->image = 0; dec->chantocmptlut = 0; dec->cmap = 0; dec->colr = 0; return dec; } static void jp2_dec_destroy(jp2_dec_t *dec) { if (dec->ihdr) { jp2_box_destroy(dec->ihdr); } if (dec->bpcc) { jp2_box_destroy(dec->bpcc); } if (dec->cdef) { jp2_box_destroy(dec->cdef); } if (dec->pclr) { jp2_box_destroy(dec->pclr); } if (dec->image) { jas_image_destroy(dec->image); } if (dec->cmap) { jp2_box_destroy(dec->cmap); } if (dec->colr) { jp2_box_destroy(dec->colr); } if (dec->chantocmptlut) { jas_free(dec->chantocmptlut); } jas_free(dec); } static int jp2_getct(int colorspace, int type, int assoc) { if (type == 1 && assoc == 0) { return JAS_IMAGE_CT_OPACITY; } if (type == 0 && assoc >= 1 && assoc <= 65534) { switch (colorspace) { case JAS_CLRSPC_FAM_RGB: switch (assoc) { case JP2_CDEF_RGB_R: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R); case JP2_CDEF_RGB_G: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G); case JP2_CDEF_RGB_B: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B); } break; case JAS_CLRSPC_FAM_YCBCR: switch (assoc) { case JP2_CDEF_YCBCR_Y: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y); case JP2_CDEF_YCBCR_CB: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB); case JP2_CDEF_YCBCR_CR: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR); } break; case JAS_CLRSPC_FAM_GRAY: switch (assoc) { case JP2_CDEF_GRAY_Y: return JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y); } break; default: return JAS_IMAGE_CT_COLOR(assoc - 1); } } return JAS_IMAGE_CT_UNKNOWN; } static int jp2_getcs(jp2_colr_t *colr) { if (colr->method == JP2_COLR_ENUM) { switch (colr->csid) { case JP2_COLR_SRGB: return JAS_CLRSPC_SRGB; case JP2_COLR_SYCC: return JAS_CLRSPC_SYCBCR; case JP2_COLR_SGRAY: return JAS_CLRSPC_SGRAY; } } return JAS_CLRSPC_UNKNOWN; } static int fromiccpcs(int cs) { switch (cs) { case ICC_CS_RGB: return JAS_CLRSPC_GENRGB; case ICC_CS_YCBCR: return JAS_CLRSPC_GENYCBCR; case ICC_CS_GRAY: return JAS_CLRSPC_GENGRAY; } return JAS_CLRSPC_UNKNOWN; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1984_1
crossvul-cpp_data_good_4541_0
/* pb_decode.c -- decode a protobuf using minimal resources * * 2011 Petteri Aimonen <jpa@kapsi.fi> */ /* Use the GCC warn_unused_result attribute to check that all return values * are propagated correctly. On other compilers and gcc before 3.4.0 just * ignore the annotation. */ #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) #define checkreturn #else #define checkreturn __attribute__((warn_unused_result)) #endif #include "pb.h" #include "pb_decode.h" #include "pb_common.h" /************************************** * Declarations internal to this file * **************************************/ typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn; static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size); static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension); static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type); static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn find_extension_field(pb_field_iter_t *iter); static void pb_field_set_to_default(pb_field_iter_t *iter); static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct); static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof); static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_skip_varint(pb_istream_t *stream); static bool checkreturn pb_skip_string(pb_istream_t *stream); #ifdef PB_ENABLE_MALLOC static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size); static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter); static void pb_release_single_field(const pb_field_iter_t *iter); #endif #ifdef PB_WITHOUT_64BIT #define pb_int64_t int32_t #define pb_uint64_t uint32_t #else #define pb_int64_t int64_t #define pb_uint64_t uint64_t #endif /* --- Function pointers to field decoders --- * Order in the array must match pb_action_t LTYPE numbering. */ static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = { &pb_dec_bool, &pb_dec_varint, &pb_dec_uvarint, &pb_dec_svarint, &pb_dec_fixed32, &pb_dec_fixed64, &pb_dec_bytes, &pb_dec_string, &pb_dec_submessage, NULL, /* extensions */ &pb_dec_fixed_length_bytes }; /******************************* * pb_istream_t implementation * *******************************/ static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) { size_t i; const pb_byte_t *source = (const pb_byte_t*)stream->state; stream->state = (pb_byte_t*)stream->state + count; if (buf != NULL) { for (i = 0; i < count; i++) buf[i] = source[i]; } return true; } bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) { if (count == 0) return true; #ifndef PB_BUFFER_ONLY if (buf == NULL && stream->callback != buf_read) { /* Skip input bytes */ pb_byte_t tmp[16]; while (count > 16) { if (!pb_read(stream, tmp, 16)) return false; count -= 16; } return pb_read(stream, tmp, count); } #endif if (stream->bytes_left < count) PB_RETURN_ERROR(stream, "end-of-stream"); #ifndef PB_BUFFER_ONLY if (!stream->callback(stream, buf, count)) PB_RETURN_ERROR(stream, "io error"); #else if (!buf_read(stream, buf, count)) return false; #endif stream->bytes_left -= count; return true; } /* Read a single byte from input stream. buf may not be NULL. * This is an optimization for the varint decoding. */ static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf) { if (stream->bytes_left == 0) PB_RETURN_ERROR(stream, "end-of-stream"); #ifndef PB_BUFFER_ONLY if (!stream->callback(stream, buf, 1)) PB_RETURN_ERROR(stream, "io error"); #else *buf = *(const pb_byte_t*)stream->state; stream->state = (pb_byte_t*)stream->state + 1; #endif stream->bytes_left--; return true; } pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize) { pb_istream_t stream; /* Cast away the const from buf without a compiler error. We are * careful to use it only in a const manner in the callbacks. */ union { void *state; const void *c_state; } state; #ifdef PB_BUFFER_ONLY stream.callback = NULL; #else stream.callback = &buf_read; #endif state.c_state = buf; stream.state = state.state; stream.bytes_left = bufsize; #ifndef PB_NO_ERRMSG stream.errmsg = NULL; #endif return stream; } /******************** * Helper functions * ********************/ static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof) { pb_byte_t byte; uint32_t result; if (!pb_readbyte(stream, &byte)) { if (stream->bytes_left == 0) { if (eof) { *eof = true; } } return false; } if ((byte & 0x80) == 0) { /* Quick case, 1 byte value */ result = byte; } else { /* Multibyte case */ uint_fast8_t bitpos = 7; result = byte & 0x7F; do { if (!pb_readbyte(stream, &byte)) return false; if (bitpos >= 32) { /* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */ uint8_t sign_extension = (bitpos < 63) ? 0xFF : 0x01; if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension)) { PB_RETURN_ERROR(stream, "varint overflow"); } } else { result |= (uint32_t)(byte & 0x7F) << bitpos; } bitpos = (uint_fast8_t)(bitpos + 7); } while (byte & 0x80); if (bitpos == 35 && (byte & 0x70) != 0) { /* The last byte was at bitpos=28, so only bottom 4 bits fit. */ PB_RETURN_ERROR(stream, "varint overflow"); } } *dest = result; return true; } bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest) { return pb_decode_varint32_eof(stream, dest, NULL); } #ifndef PB_WITHOUT_64BIT bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest) { pb_byte_t byte; uint_fast8_t bitpos = 0; uint64_t result = 0; do { if (bitpos >= 64) PB_RETURN_ERROR(stream, "varint overflow"); if (!pb_readbyte(stream, &byte)) return false; result |= (uint64_t)(byte & 0x7F) << bitpos; bitpos = (uint_fast8_t)(bitpos + 7); } while (byte & 0x80); *dest = result; return true; } #endif bool checkreturn pb_skip_varint(pb_istream_t *stream) { pb_byte_t byte; do { if (!pb_read(stream, &byte, 1)) return false; } while (byte & 0x80); return true; } bool checkreturn pb_skip_string(pb_istream_t *stream) { uint32_t length; if (!pb_decode_varint32(stream, &length)) return false; return pb_read(stream, NULL, length); } bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof) { uint32_t temp; *eof = false; *wire_type = (pb_wire_type_t) 0; *tag = 0; if (!pb_decode_varint32_eof(stream, &temp, eof)) { return false; } if (temp == 0) { *eof = true; /* Special feature: allow 0-terminated messages. */ return false; } *tag = temp >> 3; *wire_type = (pb_wire_type_t)(temp & 7); return true; } bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type) { switch (wire_type) { case PB_WT_VARINT: return pb_skip_varint(stream); case PB_WT_64BIT: return pb_read(stream, NULL, 8); case PB_WT_STRING: return pb_skip_string(stream); case PB_WT_32BIT: return pb_read(stream, NULL, 4); default: PB_RETURN_ERROR(stream, "invalid wire_type"); } } /* Read a raw value to buffer, for the purpose of passing it to callback as * a substream. Size is maximum size on call, and actual size on return. */ static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size) { size_t max_size = *size; switch (wire_type) { case PB_WT_VARINT: *size = 0; do { (*size)++; if (*size > max_size) return false; if (!pb_read(stream, buf, 1)) return false; } while (*buf++ & 0x80); return true; case PB_WT_64BIT: *size = 8; return pb_read(stream, buf, 8); case PB_WT_32BIT: *size = 4; return pb_read(stream, buf, 4); case PB_WT_STRING: /* Calling read_raw_value with a PB_WT_STRING is an error. * Explicitly handle this case and fallthrough to default to avoid * compiler warnings. */ default: PB_RETURN_ERROR(stream, "invalid wire_type"); } } /* Decode string length from stream and return a substream with limited length. * Remember to close the substream using pb_close_string_substream(). */ bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream) { uint32_t size; if (!pb_decode_varint32(stream, &size)) return false; *substream = *stream; if (substream->bytes_left < size) PB_RETURN_ERROR(stream, "parent stream too short"); substream->bytes_left = size; stream->bytes_left -= size; return true; } bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream) { if (substream->bytes_left) { if (!pb_read(substream, NULL, substream->bytes_left)) return false; } stream->state = substream->state; #ifndef PB_NO_ERRMSG stream->errmsg = substream->errmsg; #endif return true; } /************************* * Decode a single field * *************************/ static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_type_t type; pb_decoder_t func; type = iter->pos->type; func = PB_DECODERS[PB_LTYPE(type)]; switch (PB_HTYPE(type)) { case PB_HTYPE_REQUIRED: return func(stream, iter->pos, iter->pData); case PB_HTYPE_OPTIONAL: if (iter->pSize != iter->pData) *(bool*)iter->pSize = true; return func(stream, iter->pos, iter->pData); case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array */ bool status = true; pb_size_t *size = (pb_size_t*)iter->pSize; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left > 0 && *size < iter->pos->array_size) { void *pItem = (char*)iter->pData + iter->pos->data_size * (*size); if (!func(&substream, iter->pos, pItem)) { status = false; break; } (*size)++; } if (substream.bytes_left != 0) PB_RETURN_ERROR(stream, "array overflow"); if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Repeated field */ pb_size_t *size = (pb_size_t*)iter->pSize; char *pItem = (char*)iter->pData + iter->pos->data_size * (*size); if ((*size)++ >= iter->pos->array_size) PB_RETURN_ERROR(stream, "array overflow"); return func(stream, iter->pos, pItem); } case PB_HTYPE_ONEOF: *(pb_size_t*)iter->pSize = iter->pos->tag; if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) { /* We memset to zero so that any callbacks are set to NULL. * Then set any default values. */ memset(iter->pData, 0, iter->pos->data_size); pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData); } return func(stream, iter->pos, iter->pData); default: PB_RETURN_ERROR(stream, "invalid field type"); } } #ifdef PB_ENABLE_MALLOC /* Allocate storage for the field and store the pointer at iter->pData. * array_size is the number of entries to reserve in an array. * Zero size is not allowed, use pb_free() for releasing. */ static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size) { void *ptr = *(void**)pData; if (data_size == 0 || array_size == 0) PB_RETURN_ERROR(stream, "invalid size"); #ifdef __AVR__ /* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284 * Realloc to size of 1 byte can cause corruption of the malloc structures. */ if (data_size == 1 && array_size == 1) { data_size = 2; } #endif /* Check for multiplication overflows. * This code avoids the costly division if the sizes are small enough. * Multiplication is safe as long as only half of bits are set * in either multiplicand. */ { const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4); if (data_size >= check_limit || array_size >= check_limit) { const size_t size_max = (size_t)-1; if (size_max / array_size < data_size) { PB_RETURN_ERROR(stream, "size too large"); } } } /* Allocate new or expand previous allocation */ /* Note: on failure the old pointer will remain in the structure, * the message must be freed by caller also on error return. */ ptr = pb_realloc(ptr, array_size * data_size); if (ptr == NULL) PB_RETURN_ERROR(stream, "realloc failed"); *(void**)pData = ptr; return true; } /* Clear a newly allocated item in case it contains a pointer, or is a submessage. */ static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter) { if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING || PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES) { *(void**)pItem = NULL; } else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) { /* We memset to zero so that any callbacks are set to NULL. * Then set any default values. */ memset(pItem, 0, iter->pos->data_size); pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem); } } #endif static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { #ifndef PB_ENABLE_MALLOC PB_UNUSED(wire_type); PB_UNUSED(iter); PB_RETURN_ERROR(stream, "no malloc support"); #else pb_type_t type; pb_decoder_t func; type = iter->pos->type; func = PB_DECODERS[PB_LTYPE(type)]; switch (PB_HTYPE(type)) { case PB_HTYPE_REQUIRED: case PB_HTYPE_OPTIONAL: case PB_HTYPE_ONEOF: if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && *(void**)iter->pData != NULL) { /* Duplicate field, have to release the old allocation first. */ pb_release_single_field(iter); } if (PB_HTYPE(type) == PB_HTYPE_ONEOF) { *(pb_size_t*)iter->pSize = iter->pos->tag; } if (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES) { return func(stream, iter->pos, iter->pData); } else { if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1)) return false; initialize_pointer_field(*(void**)iter->pData, iter); return func(stream, iter->pos, *(void**)iter->pData); } case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array, multiple items come in at once. */ bool status = true; pb_size_t *size = (pb_size_t*)iter->pSize; size_t allocated_size = *size; void *pItem; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left) { if ((size_t)*size + 1 > allocated_size) { /* Allocate more storage. This tries to guess the * number of remaining entries. Round the division * upwards. */ allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1; if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size)) { status = false; break; } } /* Decode the array entry */ pItem = *(char**)iter->pData + iter->pos->data_size * (*size); initialize_pointer_field(pItem, iter); if (!func(&substream, iter->pos, pItem)) { status = false; break; } if (*size == PB_SIZE_MAX) { #ifndef PB_NO_ERRMSG stream->errmsg = "too many array entries"; #endif status = false; break; } (*size)++; } if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Normal repeated field, i.e. only one item at a time. */ pb_size_t *size = (pb_size_t*)iter->pSize; void *pItem; if (*size == PB_SIZE_MAX) PB_RETURN_ERROR(stream, "too many array entries"); if (!allocate_field(stream, iter->pData, iter->pos->data_size, (size_t)(*size + 1))) return false; pItem = *(char**)iter->pData + iter->pos->data_size * (*size); (*size)++; initialize_pointer_field(pItem, iter); return func(stream, iter->pos, pItem); } default: PB_RETURN_ERROR(stream, "invalid field type"); } #endif } static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_callback_t *pCallback = (pb_callback_t*)iter->pData; #ifdef PB_OLD_CALLBACK_STYLE void *arg; #else void **arg; #endif if (pCallback == NULL || pCallback->funcs.decode == NULL) return pb_skip_field(stream, wire_type); #ifdef PB_OLD_CALLBACK_STYLE arg = pCallback->arg; #else arg = &(pCallback->arg); #endif if (wire_type == PB_WT_STRING) { pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; do { if (!pCallback->funcs.decode(&substream, iter->pos, arg)) PB_RETURN_ERROR(stream, "callback failed"); } while (substream.bytes_left); if (!pb_close_string_substream(stream, &substream)) return false; return true; } else { /* Copy the single scalar value to stack. * This is required so that we can limit the stream length, * which in turn allows to use same callback for packed and * not-packed fields. */ pb_istream_t substream; pb_byte_t buffer[10]; size_t size = sizeof(buffer); if (!read_raw_value(stream, wire_type, buffer, &size)) return false; substream = pb_istream_from_buffer(buffer, size); return pCallback->funcs.decode(&substream, iter->pos, arg); } } static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { #ifdef PB_ENABLE_MALLOC /* When decoding an oneof field, check if there is old data that must be * released first. */ if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF) { if (!pb_release_union_field(stream, iter)) return false; } #endif switch (PB_ATYPE(iter->pos->type)) { case PB_ATYPE_STATIC: return decode_static_field(stream, wire_type, iter); case PB_ATYPE_POINTER: return decode_pointer_field(stream, wire_type, iter); case PB_ATYPE_CALLBACK: return decode_callback_field(stream, wire_type, iter); default: PB_RETURN_ERROR(stream, "invalid field type"); } } static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension) { /* Fake a field iterator for the extension field. * It is not actually safe to advance this iterator, but decode_field * will not even try to. */ const pb_field_t *field = (const pb_field_t*)extension->type->arg; (void)pb_field_iter_begin(iter, field, extension->dest); iter->pData = extension->dest; iter->pSize = &extension->found; if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { /* For pointer extensions, the pointer is stored directly * in the extension structure. This avoids having an extra * indirection. */ iter->pData = &extension->dest; } } /* Default handler for extension fields. Expects a pb_field_t structure * in extension->type->arg. */ static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type) { const pb_field_t *field = (const pb_field_t*)extension->type->arg; pb_field_iter_t iter; if (field->tag != tag) return true; iter_from_extension(&iter, extension); extension->found = true; return decode_field(stream, wire_type, &iter); } /* Try to decode an unknown field as an extension field. Tries each extension * decoder in turn, until one of them handles the field or loop ends. */ static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_extension_t *extension = *(pb_extension_t* const *)iter->pData; size_t pos = stream->bytes_left; while (extension != NULL && pos == stream->bytes_left) { bool status; if (extension->type->decode) status = extension->type->decode(stream, extension, tag, wire_type); else status = default_extension_decoder(stream, extension, tag, wire_type); if (!status) return false; extension = extension->next; } return true; } /* Step through the iterator until an extension field is found or until all * entries have been checked. There can be only one extension field per * message. Returns false if no extension field is found. */ static bool checkreturn find_extension_field(pb_field_iter_t *iter) { const pb_field_t *start = iter->pos; do { if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION) return true; (void)pb_field_iter_next(iter); } while (iter->pos != start); return false; } /* Initialize message fields to default values, recursively */ static void pb_field_set_to_default(pb_field_iter_t *iter) { pb_type_t type; type = iter->pos->type; if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) { pb_extension_t *ext = *(pb_extension_t* const *)iter->pData; while (ext != NULL) { pb_field_iter_t ext_iter; ext->found = false; iter_from_extension(&ext_iter, ext); pb_field_set_to_default(&ext_iter); ext = ext->next; } } else if (PB_ATYPE(type) == PB_ATYPE_STATIC) { bool init_data = true; if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData) { /* Set has_field to false. Still initialize the optional field * itself also. */ *(bool*)iter->pSize = false; } else if (PB_HTYPE(type) == PB_HTYPE_REPEATED || PB_HTYPE(type) == PB_HTYPE_ONEOF) { /* REPEATED: Set array count to 0, no need to initialize contents. ONEOF: Set which_field to 0. */ *(pb_size_t*)iter->pSize = 0; init_data = false; } if (init_data) { if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) { /* Initialize submessage to defaults */ pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData); } else if (iter->pos->ptr != NULL) { /* Initialize to default value */ memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size); } else { /* Initialize to zeros */ memset(iter->pData, 0, iter->pos->data_size); } } } else if (PB_ATYPE(type) == PB_ATYPE_POINTER) { /* Initialize the pointer to NULL. */ *(void**)iter->pData = NULL; /* Initialize array count to 0. */ if (PB_HTYPE(type) == PB_HTYPE_REPEATED || PB_HTYPE(type) == PB_HTYPE_ONEOF) { *(pb_size_t*)iter->pSize = 0; } } else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK) { /* Don't overwrite callback */ } } static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct) { pb_field_iter_t iter; if (!pb_field_iter_begin(&iter, fields, dest_struct)) return; /* Empty message type */ do { pb_field_set_to_default(&iter); } while (pb_field_iter_next(&iter)); } /********************* * Decode all fields * *********************/ bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0}; const uint32_t allbits = ~(uint32_t)0; uint32_t extension_range_start = 0; pb_field_iter_t iter; /* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed * count field. This can only handle _one_ repeated fixed count field that * is unpacked and unordered among other (non repeated fixed count) fields. */ const pb_field_t *fixed_count_field = NULL; pb_size_t fixed_count_size = 0; /* Return value ignored, as empty message types will be correctly handled by * pb_field_iter_find() anyway. */ (void)pb_field_iter_begin(&iter, fields, dest_struct); while (stream->bytes_left) { uint32_t tag; pb_wire_type_t wire_type; bool eof; if (!pb_decode_tag(stream, &wire_type, &tag, &eof)) { if (eof) break; else return false; } if (!pb_field_iter_find(&iter, tag)) { /* No match found, check if it matches an extension. */ if (tag >= extension_range_start) { if (!find_extension_field(&iter)) extension_range_start = (uint32_t)-1; else extension_range_start = iter.pos->tag; if (tag >= extension_range_start) { size_t pos = stream->bytes_left; if (!decode_extension(stream, tag, wire_type, &iter)) return false; if (pos != stream->bytes_left) { /* The field was handled */ continue; } } } /* No match found, skip data */ if (!pb_skip_field(stream, wire_type)) return false; continue; } /* If a repeated fixed count field was found, get size from * 'fixed_count_field' as there is no counter contained in the struct. */ if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED && iter.pSize == iter.pData) { if (fixed_count_field != iter.pos) { /* If the new fixed count field does not match the previous one, * check that the previous one is NULL or that it finished * receiving all the expected data. */ if (fixed_count_field != NULL && fixed_count_size != fixed_count_field->array_size) { PB_RETURN_ERROR(stream, "wrong size for fixed count field"); } fixed_count_field = iter.pos; fixed_count_size = 0; } iter.pSize = &fixed_count_size; } if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED && iter.required_field_index < PB_MAX_REQUIRED_FIELDS) { uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31)); fields_seen[iter.required_field_index >> 5] |= tmp; } if (!decode_field(stream, wire_type, &iter)) return false; } /* Check that all elements of the last decoded fixed count field were present. */ if (fixed_count_field != NULL && fixed_count_size != fixed_count_field->array_size) { PB_RETURN_ERROR(stream, "wrong size for fixed count field"); } /* Check that all required fields were present. */ { /* First figure out the number of required fields by * seeking to the end of the field array. Usually we * are already close to end after decoding. */ unsigned req_field_count; pb_type_t last_type; unsigned i; do { req_field_count = iter.required_field_index; last_type = iter.pos->type; } while (pb_field_iter_next(&iter)); /* Fixup if last field was also required. */ if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0) req_field_count++; if (req_field_count > PB_MAX_REQUIRED_FIELDS) req_field_count = PB_MAX_REQUIRED_FIELDS; if (req_field_count > 0) { /* Check the whole words */ for (i = 0; i < (req_field_count >> 5); i++) { if (fields_seen[i] != allbits) PB_RETURN_ERROR(stream, "missing required field"); } /* Check the remaining bits (if any) */ if ((req_field_count & 31) != 0) { if (fields_seen[req_field_count >> 5] != (allbits >> (32 - (req_field_count & 31)))) { PB_RETURN_ERROR(stream, "missing required field"); } } } } return true; } bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { bool status; pb_message_set_to_defaults(fields, dest_struct); status = pb_decode_noinit(stream, fields, dest_struct); #ifdef PB_ENABLE_MALLOC if (!status) pb_release(fields, dest_struct); #endif return status; } bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { pb_istream_t substream; bool status; if (!pb_make_string_substream(stream, &substream)) return false; status = pb_decode_noinit(&substream, fields, dest_struct); if (!pb_close_string_substream(stream, &substream)) return false; return status; } bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { pb_istream_t substream; bool status; if (!pb_make_string_substream(stream, &substream)) return false; status = pb_decode(&substream, fields, dest_struct); if (!pb_close_string_substream(stream, &substream)) return false; return status; } bool pb_decode_nullterminated(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { /* This behaviour will be separated in nanopb-0.4.0, see issue #278. */ return pb_decode(stream, fields, dest_struct); } #ifdef PB_ENABLE_MALLOC /* Given an oneof field, if there has already been a field inside this oneof, * release it before overwriting with a different one. */ static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter) { pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */ pb_size_t new_tag = iter->pos->tag; /* New which_ value */ if (old_tag == 0) return true; /* Ok, no old data in union */ if (old_tag == new_tag) return true; /* Ok, old data is of same type => merge */ /* Release old data. The find can fail if the message struct contains * invalid data. */ if (!pb_field_iter_find(iter, old_tag)) PB_RETURN_ERROR(stream, "invalid union tag"); pb_release_single_field(iter); /* Restore iterator to where it should be. * This shouldn't fail unless the pb_field_t structure is corrupted. */ if (!pb_field_iter_find(iter, new_tag)) PB_RETURN_ERROR(stream, "iterator error"); return true; } static void pb_release_single_field(const pb_field_iter_t *iter) { pb_type_t type; type = iter->pos->type; if (PB_HTYPE(type) == PB_HTYPE_ONEOF) { if (*(pb_size_t*)iter->pSize != iter->pos->tag) return; /* This is not the current field in the union */ } /* Release anything contained inside an extension or submsg. * This has to be done even if the submsg itself is statically * allocated. */ if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) { /* Release fields from all extensions in the linked list */ pb_extension_t *ext = *(pb_extension_t**)iter->pData; while (ext != NULL) { pb_field_iter_t ext_iter; iter_from_extension(&ext_iter, ext); pb_release_single_field(&ext_iter); ext = ext->next; } } else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && PB_ATYPE(type) != PB_ATYPE_CALLBACK) { /* Release fields in submessage or submsg array */ void *pItem = iter->pData; pb_size_t count = 1; if (PB_ATYPE(type) == PB_ATYPE_POINTER) { pItem = *(void**)iter->pData; } if (PB_HTYPE(type) == PB_HTYPE_REPEATED) { if (PB_ATYPE(type) == PB_ATYPE_STATIC && iter->pSize == iter->pData) { /* No _count field so use size of the array */ count = iter->pos->array_size; } else { count = *(pb_size_t*)iter->pSize; } if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size) { /* Protect against corrupted _count fields */ count = iter->pos->array_size; } } if (pItem) { while (count--) { pb_release((const pb_field_t*)iter->pos->ptr, pItem); pItem = (char*)pItem + iter->pos->data_size; } } } if (PB_ATYPE(type) == PB_ATYPE_POINTER) { if (PB_HTYPE(type) == PB_HTYPE_REPEATED && (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES)) { /* Release entries in repeated string or bytes array */ void **pItem = *(void***)iter->pData; pb_size_t count = *(pb_size_t*)iter->pSize; while (count--) { pb_free(*pItem); *pItem++ = NULL; } } if (PB_HTYPE(type) == PB_HTYPE_REPEATED) { /* We are going to release the array, so set the size to 0 */ *(pb_size_t*)iter->pSize = 0; } /* Release main item */ pb_free(*(void**)iter->pData); *(void**)iter->pData = NULL; } } void pb_release(const pb_field_t fields[], void *dest_struct) { pb_field_iter_t iter; if (!dest_struct) return; /* Ignore NULL pointers, similar to free() */ if (!pb_field_iter_begin(&iter, fields, dest_struct)) return; /* Empty message type */ do { pb_release_single_field(&iter); } while (pb_field_iter_next(&iter)); } #endif /* Field decoders */ bool pb_decode_bool(pb_istream_t *stream, bool *dest) { return pb_dec_bool(stream, NULL, (void*)dest); } bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest) { pb_uint64_t value; if (!pb_decode_varint(stream, &value)) return false; if (value & 1) *dest = (pb_int64_t)(~(value >> 1)); else *dest = (pb_int64_t)(value >> 1); return true; } bool pb_decode_fixed32(pb_istream_t *stream, void *dest) { pb_byte_t bytes[4]; if (!pb_read(stream, bytes, 4)) return false; *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) | ((uint32_t)bytes[1] << 8) | ((uint32_t)bytes[2] << 16) | ((uint32_t)bytes[3] << 24); return true; } #ifndef PB_WITHOUT_64BIT bool pb_decode_fixed64(pb_istream_t *stream, void *dest) { pb_byte_t bytes[8]; if (!pb_read(stream, bytes, 8)) return false; *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) | ((uint64_t)bytes[1] << 8) | ((uint64_t)bytes[2] << 16) | ((uint64_t)bytes[3] << 24) | ((uint64_t)bytes[4] << 32) | ((uint64_t)bytes[5] << 40) | ((uint64_t)bytes[6] << 48) | ((uint64_t)bytes[7] << 56); return true; } #endif static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t value; PB_UNUSED(field); if (!pb_decode_varint32(stream, &value)) return false; *(bool*)dest = (value != 0); return true; } static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest) { pb_uint64_t value; pb_int64_t svalue; pb_int64_t clamped; if (!pb_decode_varint(stream, &value)) return false; /* See issue 97: Google's C++ protobuf allows negative varint values to * be cast as int32_t, instead of the int64_t that should be used when * encoding. Previous nanopb versions had a bug in encoding. In order to * not break decoding of such messages, we cast <=32 bit fields to * int32_t first to get the sign correct. */ if (field->data_size == sizeof(pb_int64_t)) svalue = (pb_int64_t)value; else svalue = (int32_t)value; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_int64_t)) clamped = *(pb_int64_t*)dest = svalue; else if (field->data_size == sizeof(int32_t)) clamped = *(int32_t*)dest = (int32_t)svalue; else if (field->data_size == sizeof(int_least16_t)) clamped = *(int_least16_t*)dest = (int_least16_t)svalue; else if (field->data_size == sizeof(int_least8_t)) clamped = *(int_least8_t*)dest = (int_least8_t)svalue; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != svalue) PB_RETURN_ERROR(stream, "integer too large"); return true; } static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest) { pb_uint64_t value, clamped; if (!pb_decode_varint(stream, &value)) return false; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_uint64_t)) clamped = *(pb_uint64_t*)dest = value; else if (field->data_size == sizeof(uint32_t)) clamped = *(uint32_t*)dest = (uint32_t)value; else if (field->data_size == sizeof(uint_least16_t)) clamped = *(uint_least16_t*)dest = (uint_least16_t)value; else if (field->data_size == sizeof(uint_least8_t)) clamped = *(uint_least8_t*)dest = (uint_least8_t)value; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != value) PB_RETURN_ERROR(stream, "integer too large"); return true; } static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest) { pb_int64_t value, clamped; if (!pb_decode_svarint(stream, &value)) return false; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_int64_t)) clamped = *(pb_int64_t*)dest = value; else if (field->data_size == sizeof(int32_t)) clamped = *(int32_t*)dest = (int32_t)value; else if (field->data_size == sizeof(int_least16_t)) clamped = *(int_least16_t*)dest = (int_least16_t)value; else if (field->data_size == sizeof(int_least8_t)) clamped = *(int_least8_t*)dest = (int_least8_t)value; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != value) PB_RETURN_ERROR(stream, "integer too large"); return true; } static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest) { PB_UNUSED(field); return pb_decode_fixed32(stream, dest); } static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest) { PB_UNUSED(field); #ifndef PB_WITHOUT_64BIT return pb_decode_fixed64(stream, dest); #else PB_UNUSED(dest); PB_RETURN_ERROR(stream, "no 64bit support"); #endif } static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t size; size_t alloc_size; pb_bytes_array_t *bdest; if (!pb_decode_varint32(stream, &size)) return false; if (size > PB_SIZE_MAX) PB_RETURN_ERROR(stream, "bytes overflow"); alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size); if (size > alloc_size) PB_RETURN_ERROR(stream, "size too large"); if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { #ifndef PB_ENABLE_MALLOC PB_RETURN_ERROR(stream, "no malloc support"); #else if (!allocate_field(stream, dest, alloc_size, 1)) return false; bdest = *(pb_bytes_array_t**)dest; #endif } else { if (alloc_size > field->data_size) PB_RETURN_ERROR(stream, "bytes overflow"); bdest = (pb_bytes_array_t*)dest; } bdest->size = (pb_size_t)size; return pb_read(stream, bdest->bytes, size); } static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t size; size_t alloc_size; bool status; if (!pb_decode_varint32(stream, &size)) return false; /* Space for null terminator */ alloc_size = size + 1; if (alloc_size < size) PB_RETURN_ERROR(stream, "size too large"); if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { #ifndef PB_ENABLE_MALLOC PB_RETURN_ERROR(stream, "no malloc support"); #else if (!allocate_field(stream, dest, alloc_size, 1)) return false; dest = *(void**)dest; #endif } else { if (alloc_size > field->data_size) PB_RETURN_ERROR(stream, "string overflow"); } status = pb_read(stream, (pb_byte_t*)dest, size); *((pb_byte_t*)dest + size) = 0; return status; } static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest) { bool status; pb_istream_t substream; const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr; if (!pb_make_string_substream(stream, &substream)) return false; if (field->ptr == NULL) PB_RETURN_ERROR(stream, "invalid field descriptor"); /* New array entries need to be initialized, while required and optional * submessages have already been initialized in the top-level pb_decode. */ if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED) status = pb_decode(&substream, submsg_fields, dest); else status = pb_decode_noinit(&substream, submsg_fields, dest); if (!pb_close_string_substream(stream, &substream)) return false; return status; } static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t size; if (!pb_decode_varint32(stream, &size)) return false; if (size > PB_SIZE_MAX) PB_RETURN_ERROR(stream, "bytes overflow"); if (size == 0) { /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */ memset(dest, 0, field->data_size); return true; } if (size != field->data_size) PB_RETURN_ERROR(stream, "incorrect fixed length bytes size"); return pb_read(stream, (pb_byte_t*)dest, field->data_size); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_4541_0
crossvul-cpp_data_good_5201_4
/* We test that a 8bpp TGA file will be gracefully rejected by gdImageCreateFromTga(). */ #include <stdio.h> #include "gd.h" #include "gdtest.h" int main(int argc, char **argv) { gdImagePtr im; FILE *fp = gdTestFileOpen("tga/bug00247a.tga"); im = gdImageCreateFromTga(fp); gdTestAssert(im == NULL); fclose(fp); return gdNumFailures(); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5201_4
crossvul-cpp_data_good_2729_0
/* * Copyright (C) 1999 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */ /* NLRI "prefix length" from RFC 2858 Section 4. */ ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ /* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits. * RFC 4684 Section 4 defines the layout of "origin AS" and "route * target" fields inside the "prefix" depending on its length. */ if (0 == plen) { /* Without "origin AS", without "route target". */ snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; /* With at least "origin AS", possibly with "route target". */ ND_TCHECK_32BITS(pptr + 1); as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1)); plen-=32; /* adjust prefix length */ if (64 < plen) return -1; /* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 } * and gives the number of octets in the variable-length "route * target" field inside this NLRI "prefix". Look for it. */ memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[5], (plen + 7) / 8); memcpy(&route_target, &pptr[5], (plen + 7) / 8); /* Which specification says to do this? */ if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", asbuf, bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; ND_TCHECK2(tptr[0], 5); tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; tlen = len; while (tlen >= 3) { ND_TCHECK2(tptr[0], 3); type = *tptr; length = EXTRACT_16BITS(tptr+1); tptr += 3; tlen -= 3; ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); if (length < 3) goto trunc; length -= 3; /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length); switch (type) { case BGP_AIGP_TLV: if (length < 8) goto trunc; ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr,"\n\t ", length); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2729_0
crossvul-cpp_data_bad_3945_0
/** * WinPR: Windows Portable Runtime * NTLM Security Package (Message) * * Copyright 2011-2014 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 "ntlm.h" #include "../sspi.h" #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/stream.h> #include <winpr/sysinfo.h> #include "ntlm_compute.h" #include "ntlm_message.h" #include "../log.h" #define TAG WINPR_TAG("sspi.NTLM") static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' }; #ifdef WITH_DEBUG_NTLM static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56", "NTLMSSP_NEGOTIATE_KEY_EXCH", "NTLMSSP_NEGOTIATE_128", "NTLMSSP_RESERVED1", "NTLMSSP_RESERVED2", "NTLMSSP_RESERVED3", "NTLMSSP_NEGOTIATE_VERSION", "NTLMSSP_RESERVED4", "NTLMSSP_NEGOTIATE_TARGET_INFO", "NTLMSSP_REQUEST_NON_NT_SESSION_KEY", "NTLMSSP_RESERVED5", "NTLMSSP_NEGOTIATE_IDENTIFY", "NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY", "NTLMSSP_RESERVED6", "NTLMSSP_TARGET_TYPE_SERVER", "NTLMSSP_TARGET_TYPE_DOMAIN", "NTLMSSP_NEGOTIATE_ALWAYS_SIGN", "NTLMSSP_RESERVED7", "NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED", "NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED", "NTLMSSP_NEGOTIATE_ANONYMOUS", "NTLMSSP_RESERVED8", "NTLMSSP_NEGOTIATE_NTLM", "NTLMSSP_RESERVED9", "NTLMSSP_NEGOTIATE_LM_KEY", "NTLMSSP_NEGOTIATE_DATAGRAM", "NTLMSSP_NEGOTIATE_SEAL", "NTLMSSP_NEGOTIATE_SIGN", "NTLMSSP_RESERVED10", "NTLMSSP_REQUEST_TARGET", "NTLMSSP_NEGOTIATE_OEM", "NTLMSSP_NEGOTIATE_UNICODE" }; static void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, "negotiateFlags \"0x%08" PRIX32 "\"", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, "\t%s (%d),", str, (31 - i)); } } } #endif static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { if (Stream_GetRemainingLength(s) < 12) return -1; Stream_Read(s, header->Signature, 8); Stream_Read_UINT32(s, header->MessageType); if (strncmp((char*)header->Signature, NTLM_SIGNATURE, 8) != 0) return -1; return 1; } static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); } static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->MaxLen < 1) fields->MaxLen = fields->Len; Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ } static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT32 offset = fields->BufferOffset + fields->Len; if (fields->BufferOffset > UINT32_MAX - fields->Len) return -1; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE)malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } } static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } } #ifdef WITH_DEBUG_NTLM static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %" PRIu16 " MaxLen: %" PRIu16 " BufferOffset: %" PRIu32 ")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); } #endif SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } context->NegotiateFlags = message->NegotiateFlags; /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_NEGOTIATE); if (context->NTLMv2) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM; } message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; if (context->confidentiality) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; if (context->SendVersionInfo) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_get_version_info(&(message->Version)); context->NegotiateFlags = message->NegotiateFlags; /* Message Header (12 bytes) */ ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ /* DomainNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->DomainName)); /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ /* WorkstationFields (8 bytes) */ ntlm_write_message_fields(s, &(message->Workstation)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; int length; PBYTE StartOffset; PBYTE PayloadOffset; NTLM_AV_PAIR* AvTimestamp; NTLM_CHALLENGE_MESSAGE* message; ntlm_generate_client_challenge(context); message = &context->CHALLENGE_MESSAGE; ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; StartOffset = Stream_Pointer(s); if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_CHALLENGE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (Stream_GetRemainingLength(s) < 4) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateFlags = message->NegotiateFlags; if (Stream_GetRemainingLength(s) < 8) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ CopyMemory(context->ServerChallenge, message->ServerChallenge, 8); if (Stream_GetRemainingLength(s) < 8) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } /* Payload (variable) */ PayloadOffset = Stream_Pointer(s); if (message->TargetName.Len > 0) { if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } } if (message->TargetInfo.Len > 0) { size_t cbAvTimestamp; if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer; context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len; AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*)message->TargetInfo.Buffer, message->TargetInfo.Len, MsvAvTimestamp, &cbAvTimestamp); if (AvTimestamp) { PBYTE ptr = ntlm_av_pair_get_value_pointer(AvTimestamp); if (!ptr) return SEC_E_INTERNAL_ERROR; if (context->NTLMv2) context->UseMIC = TRUE; CopyMemory(context->ChallengeTimestamp, ptr, 8); } } length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len; if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); ntlm_print_negotiate_flags(context->NegotiateFlags); if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->TargetName), "TargetName"); ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); if (context->ChallengeTargetInfo.cbBuffer > 0) { WLog_DBG(TAG, "ChallengeTargetInfo (%" PRIu32 "):", context->ChallengeTargetInfo.cbBuffer); ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer, context->ChallengeTargetInfo.cbBuffer); } #endif /* AV_PAIRs */ if (context->NTLMv2) { if (ntlm_construct_authenticate_target_info(context) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } sspi_SecBufferFree(&context->ChallengeTargetInfo); context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer; context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer; } ntlm_generate_timestamp(context); /* Timestamp */ if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */ ntlm_generate_random_session_key(context); /* RandomSessionKey */ ntlm_generate_exported_session_key(context); /* ExportedSessionKey */ ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */ /* Generate signing keys */ ntlm_generate_client_signing_key(context); ntlm_generate_server_signing_key(context); /* Generate sealing keys */ ntlm_generate_client_sealing_key(context); ntlm_generate_server_sealing_key(context); /* Initialize RC4 seal state using client sealing key */ ntlm_init_rc4_seal_states(context); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "ClientChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8); WLog_DBG(TAG, "ServerChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8); WLog_DBG(TAG, "SessionBaseKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16); WLog_DBG(TAG, "KeyExchangeKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16); WLog_DBG(TAG, "ExportedSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16); WLog_DBG(TAG, "RandomSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16); WLog_DBG(TAG, "ClientSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16); WLog_DBG(TAG, "ClientSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16); WLog_DBG(TAG, "ServerSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16); WLog_DBG(TAG, "ServerSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16); WLog_DBG(TAG, "Timestamp"); winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8); #endif context->state = NTLM_STATE_AUTHENTICATE; ntlm_free_message_fields_buffer(&(message->TargetName)); Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 PayloadOffset; NTLM_CHALLENGE_MESSAGE* message; message = &context->CHALLENGE_MESSAGE; ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; ntlm_get_version_info(&(message->Version)); /* Version */ ntlm_generate_server_challenge(context); /* Server Challenge */ ntlm_generate_timestamp(context); /* Timestamp */ if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */ message->NegotiateFlags = context->NegotiateFlags; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_CHALLENGE); /* Message Header (12 bytes) */ ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) { message->TargetName.Len = (UINT16)context->TargetName.cbBuffer; message->TargetName.Buffer = (PBYTE)context->TargetName.pvBuffer; } message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) { message->TargetInfo.Len = (UINT16)context->ChallengeTargetInfo.cbBuffer; message->TargetInfo.Buffer = (PBYTE)context->ChallengeTargetInfo.pvBuffer; } PayloadOffset = 48; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) PayloadOffset += 8; message->TargetName.BufferOffset = PayloadOffset; message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len; /* TargetNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->TargetName)); Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ /* TargetInfoFields (8 bytes) */ ntlm_write_message_fields(s, &(message->TargetInfo)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */ /* Payload (variable) */ if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) ntlm_write_message_fields_buffer(s, &(message->TargetName)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) ntlm_write_message_fields_buffer(s, &(message->TargetInfo)); length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->TargetName), "TargetName"); ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); #endif context->state = NTLM_STATE_AUTHENTICATE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 flags; NTLM_AV_PAIR* AvFlags; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; flags = 0; AvFlags = NULL; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKeyFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateKeyExchange = (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE; if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) || (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len)) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } PayloadBufferOffset = Stream_GetPosition(s); if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->NtChallengeResponse.Len > 0) { size_t cbAvFlags; wStream* snt = Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len); if (!snt) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0) { Stream_Free(s, FALSE); Stream_Free(snt, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Free(snt, FALSE); context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer; context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len; sspi_SecBufferFree(&(context->ChallengeTargetInfo)); context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs; context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16); CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8); AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); } if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKey */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->EncryptedRandomSessionKey.Len > 0) { if (message->EncryptedRandomSessionKey.Len != 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer, 16); } length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; Stream_SetPosition(s, PayloadBufferOffset); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s); if (Stream_GetRemainingLength(s) < 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->MessageIntegrityCheck, 16); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")", context->AuthenticateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer, context->AuthenticateMessage.cbBuffer); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs, context->NTLMv2Response.Challenge.cbAvPairs); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { WLog_DBG(TAG, "MessageIntegrityCheck:"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif if (message->UserName.Len > 0) { credentials->identity.User = (UINT16*)malloc(message->UserName.Len); if (!credentials->identity.User) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len); credentials->identity.UserLength = message->UserName.Len / 2; } if (message->DomainName.Len > 0) { credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len); if (!credentials->identity.Domain) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.Domain, message->DomainName.Buffer, message->DomainName.Len); credentials->identity.DomainLength = message->DomainName.Len / 2; } Stream_Free(s, FALSE); /* Computations beyond this point require the NTLM hash of the password */ context->state = NTLM_STATE_COMPLETION; return SEC_I_COMPLETE_NEEDED; } /** * Send NTLMSSP AUTHENTICATE_MESSAGE.\n * AUTHENTICATE_MESSAGE @msdn{cc236643} * @param NTLM context * @param buffer */ SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (context->NTLMv2) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; if (context->SendVersionInfo) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; } if (context->UseMIC) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; if (context->SendWorkstationName) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED; if (context->confidentiality) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_get_version_info(&(message->Version)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) { message->Workstation.Len = context->Workstation.Length; message->Workstation.Buffer = (BYTE*)context->Workstation.Buffer; } if (credentials->identity.DomainLength > 0) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED; message->DomainName.Len = (UINT16)credentials->identity.DomainLength * 2; message->DomainName.Buffer = (BYTE*)credentials->identity.Domain; } message->UserName.Len = (UINT16)credentials->identity.UserLength * 2; message->UserName.Buffer = (BYTE*)credentials->identity.User; message->LmChallengeResponse.Len = (UINT16)context->LmChallengeResponse.cbBuffer; message->LmChallengeResponse.Buffer = (BYTE*)context->LmChallengeResponse.pvBuffer; message->NtChallengeResponse.Len = (UINT16)context->NtChallengeResponse.cbBuffer; message->NtChallengeResponse.Buffer = (BYTE*)context->NtChallengeResponse.pvBuffer; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) { message->EncryptedRandomSessionKey.Len = 16; message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey; } PayloadBufferOffset = 64; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) PayloadBufferOffset += 8; /* Version (8 bytes) */ if (context->UseMIC) PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */ message->DomainName.BufferOffset = PayloadBufferOffset; message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len; message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len; message->LmChallengeResponse.BufferOffset = message->Workstation.BufferOffset + message->Workstation.Len; message->NtChallengeResponse.BufferOffset = message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len; message->EncryptedRandomSessionKey.BufferOffset = message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_AUTHENTICATE); ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); /* Message Header (12 bytes) */ ntlm_write_message_fields( s, &(message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */ ntlm_write_message_fields( s, &(message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */ ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */ ntlm_write_message_fields( s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */ Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */ if (context->UseMIC) { context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s); Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */ } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */ ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */ ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */ ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ntlm_write_message_fields_buffer( s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */ length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; if (context->UseMIC) { /* Message Integrity Check */ ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16); Stream_SetPosition(s, context->MessageIntegrityCheckOffset); Stream_Write(s, message->MessageIntegrityCheck, 16); Stream_SetPosition(s, length); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); if (context->AuthenticateTargetInfo.cbBuffer > 0) { WLog_DBG(TAG, "AuthenticateTargetInfo (%" PRIu32 "):", context->AuthenticateTargetInfo.cbBuffer); ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer, context->AuthenticateTargetInfo.cbBuffer); } ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); if (context->UseMIC) { WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif context->state = NTLM_STATE_FINAL; Stream_Free(s, FALSE); return SEC_I_COMPLETE_NEEDED; } SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context) { UINT32 flags = 0; size_t cbAvFlags; NTLM_AV_PAIR* AvFlags = NULL; NTLM_AUTHENTICATE_MESSAGE* message; BYTE messageIntegrityCheck[16]; if (!context) return SEC_E_INVALID_PARAMETER; if (context->state != NTLM_STATE_COMPLETION) return SEC_E_OUT_OF_SEQUENCE; message = &context->AUTHENTICATE_MESSAGE; AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */ return SEC_E_INTERNAL_ERROR; if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */ return SEC_E_INTERNAL_ERROR; /* KeyExchangeKey */ ntlm_generate_key_exchange_key(context); /* EncryptedRandomSessionKey */ ntlm_decrypt_random_session_key(context); /* ExportedSessionKey */ ntlm_generate_exported_session_key(context); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { ZeroMemory( &((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], 16); ntlm_compute_message_integrity_check(context, messageIntegrityCheck, sizeof(messageIntegrityCheck)); CopyMemory( &((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], message->MessageIntegrityCheck, 16); if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0) { WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!"); #ifdef WITH_DEBUG_NTLM WLog_ERR(TAG, "Expected MIC:"); winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, sizeof(messageIntegrityCheck)); WLog_ERR(TAG, "Actual MIC:"); winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck, sizeof(message->MessageIntegrityCheck)); #endif return SEC_E_MESSAGE_ALTERED; } } else { /* no mic message was present https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f9e6fbc4-a953-4f24-b229-ccdcc213b9ec the mic is optional, as not supported in Windows NT, Windows 2000, Windows XP, and Windows Server 2003 and, as it seems, in the NTLMv2 implementation of Qt5. now check the NtProofString, to detect if the entered client password matches the expected password. */ #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "No MIC present, using NtProofString for verification."); #endif if (memcmp(context->NTLMv2Response.Response, context->NtProofString, 16) != 0) { WLog_ERR(TAG, "NtProofString verification failed!"); #ifdef WITH_DEBUG_NTLM WLog_ERR(TAG, "Expected NtProofString:"); winpr_HexDump(TAG, WLOG_ERROR, context->NtProofString, sizeof(context->NtProofString)); WLog_ERR(TAG, "Actual NtProofString:"); winpr_HexDump(TAG, WLOG_ERROR, context->NTLMv2Response.Response, sizeof(context->NTLMv2Response)); #endif return SEC_E_LOGON_DENIED; } } /* Generate signing keys */ ntlm_generate_client_signing_key(context); ntlm_generate_server_signing_key(context); /* Generate sealing keys */ ntlm_generate_client_sealing_key(context); ntlm_generate_server_sealing_key(context); /* Initialize RC4 seal state */ ntlm_init_rc4_seal_states(context); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "ClientChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8); WLog_DBG(TAG, "ServerChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8); WLog_DBG(TAG, "SessionBaseKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16); WLog_DBG(TAG, "KeyExchangeKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16); WLog_DBG(TAG, "ExportedSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16); WLog_DBG(TAG, "RandomSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16); WLog_DBG(TAG, "ClientSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16); WLog_DBG(TAG, "ClientSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16); WLog_DBG(TAG, "ServerSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16); WLog_DBG(TAG, "ServerSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16); WLog_DBG(TAG, "Timestamp"); winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8); #endif context->state = NTLM_STATE_FINAL; ntlm_free_message_fields_buffer(&(message->DomainName)); ntlm_free_message_fields_buffer(&(message->UserName)); ntlm_free_message_fields_buffer(&(message->Workstation)); ntlm_free_message_fields_buffer(&(message->LmChallengeResponse)); ntlm_free_message_fields_buffer(&(message->NtChallengeResponse)); ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey)); return SEC_E_OK; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3945_0
crossvul-cpp_data_bad_113_1
#include "clar_libgit2.h" #include "delta.h" void test_delta_apply__read_at_off(void) { unsigned char base[16] = { 0 }, delta[] = { 0x10, 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0x10, 0x00, 0x00 }; void *out; size_t outlen; cl_git_fail(git_delta_apply(&out, &outlen, base, sizeof(base), delta, sizeof(delta))); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_113_1
crossvul-cpp_data_bad_3131_0
/*- * Copyright (c) 2008-2014 Michihiro NAKAJIMA * 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(S) ``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(S) 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 "archive_platform.h" #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include "archive.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_private.h" #include "archive_read_private.h" #include "archive_endian.h" #define MAXMATCH 256 /* Maximum match length. */ #define MINMATCH 3 /* Minimum match length. */ /* * Literal table format: * +0 +256 +510 * +---------------+-------------------------+ * | literal code | match length | * | 0 ... 255 | MINMATCH ... MAXMATCH | * +---------------+-------------------------+ * <--- LT_BITLEN_SIZE ---> */ /* Literal table size. */ #define LT_BITLEN_SIZE (UCHAR_MAX + 1 + MAXMATCH - MINMATCH + 1) /* Position table size. * Note: this used for both position table and pre literal table.*/ #define PT_BITLEN_SIZE (3 + 16) struct lzh_dec { /* Decoding status. */ int state; /* * Window to see last 8Ki(lh5),32Ki(lh6),64Ki(lh7) bytes of decoded * data. */ int w_size; int w_mask; /* Window buffer, which is a loop buffer. */ unsigned char *w_buff; /* The insert position to the window. */ int w_pos; /* The position where we can copy decoded code from the window. */ int copy_pos; /* The length how many bytes we can copy decoded code from * the window. */ int copy_len; /* * Bit stream reader. */ struct lzh_br { #define CACHE_TYPE uint64_t #define CACHE_BITS (8 * sizeof(CACHE_TYPE)) /* Cache buffer. */ CACHE_TYPE cache_buffer; /* Indicates how many bits avail in cache_buffer. */ int cache_avail; } br; /* * Huffman coding. */ struct huffman { int len_size; int len_avail; int len_bits; int freq[17]; unsigned char *bitlen; /* * Use a index table. It's faster than searching a huffman * coding tree, which is a binary tree. But a use of a large * index table causes L1 cache read miss many times. */ #define HTBL_BITS 10 int max_bits; int shift_bits; int tbl_bits; int tree_used; int tree_avail; /* Direct access table. */ uint16_t *tbl; /* Binary tree table for extra bits over the direct access. */ struct htree_t { uint16_t left; uint16_t right; } *tree; } lt, pt; int blocks_avail; int pos_pt_len_size; int pos_pt_len_bits; int literal_pt_len_size; int literal_pt_len_bits; int reading_position; int loop; int error; }; struct lzh_stream { const unsigned char *next_in; int avail_in; int64_t total_in; const unsigned char *ref_ptr; int avail_out; int64_t total_out; struct lzh_dec *ds; }; struct lha { /* entry_bytes_remaining is the number of bytes we expect. */ int64_t entry_offset; int64_t entry_bytes_remaining; int64_t entry_unconsumed; uint16_t entry_crc_calculated; size_t header_size; /* header size */ unsigned char level; /* header level */ char method[3]; /* compress type */ int64_t compsize; /* compressed data size */ int64_t origsize; /* original file size */ int setflag; #define BIRTHTIME_IS_SET 1 #define ATIME_IS_SET 2 #define UNIX_MODE_IS_SET 4 #define CRC_IS_SET 8 time_t birthtime; long birthtime_tv_nsec; time_t mtime; long mtime_tv_nsec; time_t atime; long atime_tv_nsec; mode_t mode; int64_t uid; int64_t gid; struct archive_string uname; struct archive_string gname; uint16_t header_crc; uint16_t crc; struct archive_string_conv *sconv; struct archive_string_conv *opt_sconv; struct archive_string dirname; struct archive_string filename; struct archive_wstring ws; unsigned char dos_attr; /* Flag to mark progress that an archive was read their first header.*/ char found_first_header; /* Flag to mark that indicates an empty directory. */ char directory; /* Flags to mark progress of decompression. */ char decompress_init; char end_of_entry; char end_of_entry_cleanup; char entry_is_compressed; char format_name[64]; struct lzh_stream strm; }; /* * LHA header common member offset. */ #define H_METHOD_OFFSET 2 /* Compress type. */ #define H_ATTR_OFFSET 19 /* DOS attribute. */ #define H_LEVEL_OFFSET 20 /* Header Level. */ #define H_SIZE 22 /* Minimum header size. */ static int archive_read_format_lha_bid(struct archive_read *, int); static int archive_read_format_lha_options(struct archive_read *, const char *, const char *); static int archive_read_format_lha_read_header(struct archive_read *, struct archive_entry *); static int archive_read_format_lha_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_lha_read_data_skip(struct archive_read *); static int archive_read_format_lha_cleanup(struct archive_read *); static void lha_replace_path_separator(struct lha *, struct archive_entry *); static int lha_read_file_header_0(struct archive_read *, struct lha *); static int lha_read_file_header_1(struct archive_read *, struct lha *); static int lha_read_file_header_2(struct archive_read *, struct lha *); static int lha_read_file_header_3(struct archive_read *, struct lha *); static int lha_read_file_extended_header(struct archive_read *, struct lha *, uint16_t *, int, size_t, size_t *); static size_t lha_check_header_format(const void *); static int lha_skip_sfx(struct archive_read *); static time_t lha_dos_time(const unsigned char *); static time_t lha_win_time(uint64_t, long *); static unsigned char lha_calcsum(unsigned char, const void *, int, size_t); static int lha_parse_linkname(struct archive_string *, struct archive_string *); static int lha_read_data_none(struct archive_read *, const void **, size_t *, int64_t *); static int lha_read_data_lzh(struct archive_read *, const void **, size_t *, int64_t *); static void lha_crc16_init(void); static uint16_t lha_crc16(uint16_t, const void *, size_t); static int lzh_decode_init(struct lzh_stream *, const char *); static void lzh_decode_free(struct lzh_stream *); static int lzh_decode(struct lzh_stream *, int); static int lzh_br_fillup(struct lzh_stream *, struct lzh_br *); static int lzh_huffman_init(struct huffman *, size_t, int); static void lzh_huffman_free(struct huffman *); static int lzh_read_pt_bitlen(struct lzh_stream *, int start, int end); static int lzh_make_fake_table(struct huffman *, uint16_t); static int lzh_make_huffman_table(struct huffman *); static inline int lzh_decode_huffman(struct huffman *, unsigned); static int lzh_decode_huffman_tree(struct huffman *, unsigned, int); int archive_read_support_format_lha(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct lha *lha; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_lha"); lha = (struct lha *)calloc(1, sizeof(*lha)); if (lha == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate lha data"); return (ARCHIVE_FATAL); } archive_string_init(&lha->ws); r = __archive_read_register_format(a, lha, "lha", archive_read_format_lha_bid, archive_read_format_lha_options, archive_read_format_lha_read_header, archive_read_format_lha_read_data, archive_read_format_lha_read_data_skip, NULL, archive_read_format_lha_cleanup, NULL, NULL); if (r != ARCHIVE_OK) free(lha); return (ARCHIVE_OK); } static size_t lha_check_header_format(const void *h) { const unsigned char *p = h; size_t next_skip_bytes; switch (p[H_METHOD_OFFSET+3]) { /* * "-lh0-" ... "-lh7-" "-lhd-" * "-lzs-" "-lz5-" */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case 'd': case 's': next_skip_bytes = 4; /* b0 == 0 means the end of an LHa archive file. */ if (p[0] == 0) break; if (p[H_METHOD_OFFSET] != '-' || p[H_METHOD_OFFSET+1] != 'l' || p[H_METHOD_OFFSET+4] != '-') break; if (p[H_METHOD_OFFSET+2] == 'h') { /* "-lh?-" */ if (p[H_METHOD_OFFSET+3] == 's') break; if (p[H_LEVEL_OFFSET] == 0) return (0); if (p[H_LEVEL_OFFSET] <= 3 && p[H_ATTR_OFFSET] == 0x20) return (0); } if (p[H_METHOD_OFFSET+2] == 'z') { /* LArc extensions: -lzs-,-lz4- and -lz5- */ if (p[H_LEVEL_OFFSET] != 0) break; if (p[H_METHOD_OFFSET+3] == 's' || p[H_METHOD_OFFSET+3] == '4' || p[H_METHOD_OFFSET+3] == '5') return (0); } break; case 'h': next_skip_bytes = 1; break; case 'z': next_skip_bytes = 1; break; case 'l': next_skip_bytes = 2; break; case '-': next_skip_bytes = 3; break; default : next_skip_bytes = 4; break; } return (next_skip_bytes); } static int archive_read_format_lha_bid(struct archive_read *a, int best_bid) { const char *p; const void *buff; ssize_t bytes_avail, offset, window; size_t next; /* If there's already a better bid than we can ever make, don't bother testing. */ if (best_bid > 30) return (-1); if ((p = __archive_read_ahead(a, H_SIZE, NULL)) == NULL) return (-1); if (lha_check_header_format(p) == 0) return (30); if (p[0] == 'M' && p[1] == 'Z') { /* PE file */ offset = 0; window = 4096; while (offset < (1024 * 20)) { buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < (H_SIZE + 3)) return (0); continue; } p = (const char *)buff + offset; while (p + H_SIZE < (const char *)buff + bytes_avail) { if ((next = lha_check_header_format(p)) == 0) return (30); p += next; } offset = p - (const char *)buff; } } return (0); } static int archive_read_format_lha_options(struct archive_read *a, const char *key, const char *val) { struct lha *lha; int ret = ARCHIVE_FAILED; lha = (struct lha *)(a->format->data); if (strcmp(key, "hdrcharset") == 0) { if (val == NULL || val[0] == 0) archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "lha: hdrcharset option needs a character-set name"); else { lha->opt_sconv = archive_string_conversion_from_charset( &a->archive, val, 0); if (lha->opt_sconv != NULL) ret = ARCHIVE_OK; else ret = ARCHIVE_FATAL; } return (ret); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int lha_skip_sfx(struct archive_read *a) { const void *h; const char *p, *q; size_t next, skip; ssize_t bytes, window; window = 4096; for (;;) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < (H_SIZE + 3)) goto fatal; continue; } if (bytes < H_SIZE) goto fatal; p = h; q = p + bytes; /* * Scan ahead until we find something that looks * like the lha header. */ while (p + H_SIZE < q) { if ((next = lha_check_header_format(p)) == 0) { skip = p - (const char *)h; __archive_read_consume(a, skip); return (ARCHIVE_OK); } p += next; } skip = p - (const char *)h; __archive_read_consume(a, skip); } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out LHa header"); return (ARCHIVE_FATAL); } static int truncated_error(struct archive_read *a) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated LHa header"); return (ARCHIVE_FATAL); } static int archive_read_format_lha_read_header(struct archive_read *a, struct archive_entry *entry) { struct archive_string linkname; struct archive_string pathname; struct lha *lha; const unsigned char *p; const char *signature; int err; lha_crc16_init(); a->archive.archive_format = ARCHIVE_FORMAT_LHA; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "lha"; lha = (struct lha *)(a->format->data); lha->decompress_init = 0; lha->end_of_entry = 0; lha->end_of_entry_cleanup = 0; lha->entry_unconsumed = 0; if ((p = __archive_read_ahead(a, H_SIZE, NULL)) == NULL) { /* * LHa archiver added 0 to the tail of its archive file as * the mark of the end of the archive. */ signature = __archive_read_ahead(a, sizeof(signature[0]), NULL); if (signature == NULL || signature[0] == 0) return (ARCHIVE_EOF); return (truncated_error(a)); } signature = (const char *)p; if (lha->found_first_header == 0 && signature[0] == 'M' && signature[1] == 'Z') { /* This is an executable? Must be self-extracting... */ err = lha_skip_sfx(a); if (err < ARCHIVE_WARN) return (err); if ((p = __archive_read_ahead(a, sizeof(*p), NULL)) == NULL) return (truncated_error(a)); signature = (const char *)p; } /* signature[0] == 0 means the end of an LHa archive file. */ if (signature[0] == 0) return (ARCHIVE_EOF); /* * Check the header format and method type. */ if (lha_check_header_format(p) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad LHa file"); return (ARCHIVE_FATAL); } /* We've found the first header. */ lha->found_first_header = 1; /* Set a default value and common data */ lha->header_size = 0; lha->level = p[H_LEVEL_OFFSET]; lha->method[0] = p[H_METHOD_OFFSET+1]; lha->method[1] = p[H_METHOD_OFFSET+2]; lha->method[2] = p[H_METHOD_OFFSET+3]; if (memcmp(lha->method, "lhd", 3) == 0) lha->directory = 1; else lha->directory = 0; if (memcmp(lha->method, "lh0", 3) == 0 || memcmp(lha->method, "lz4", 3) == 0) lha->entry_is_compressed = 0; else lha->entry_is_compressed = 1; lha->compsize = 0; lha->origsize = 0; lha->setflag = 0; lha->birthtime = 0; lha->birthtime_tv_nsec = 0; lha->mtime = 0; lha->mtime_tv_nsec = 0; lha->atime = 0; lha->atime_tv_nsec = 0; lha->mode = (lha->directory)? 0777 : 0666; lha->uid = 0; lha->gid = 0; archive_string_empty(&lha->dirname); archive_string_empty(&lha->filename); lha->dos_attr = 0; if (lha->opt_sconv != NULL) lha->sconv = lha->opt_sconv; else lha->sconv = NULL; switch (p[H_LEVEL_OFFSET]) { case 0: err = lha_read_file_header_0(a, lha); break; case 1: err = lha_read_file_header_1(a, lha); break; case 2: err = lha_read_file_header_2(a, lha); break; case 3: err = lha_read_file_header_3(a, lha); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported LHa header level %d", p[H_LEVEL_OFFSET]); err = ARCHIVE_FATAL; break; } if (err < ARCHIVE_WARN) return (err); if (!lha->directory && archive_strlen(&lha->filename) == 0) /* The filename has not been set */ return (truncated_error(a)); /* * Make a pathname from a dirname and a filename. */ archive_string_concat(&lha->dirname, &lha->filename); archive_string_init(&pathname); archive_string_init(&linkname); archive_string_copy(&pathname, &lha->dirname); if ((lha->mode & AE_IFMT) == AE_IFLNK) { /* * Extract the symlink-name if it's included in the pathname. */ if (!lha_parse_linkname(&linkname, &pathname)) { /* We couldn't get the symlink-name. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown symlink-name"); archive_string_free(&pathname); archive_string_free(&linkname); return (ARCHIVE_FAILED); } } else { /* * Make sure a file-type is set. * The mode has been overridden if it is in the extended data. */ lha->mode = (lha->mode & ~AE_IFMT) | ((lha->directory)? AE_IFDIR: AE_IFREG); } if ((lha->setflag & UNIX_MODE_IS_SET) == 0 && (lha->dos_attr & 1) != 0) lha->mode &= ~(0222);/* read only. */ /* * Set basic file parameters. */ if (archive_entry_copy_pathname_l(entry, pathname.s, pathname.length, lha->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted " "from %s to current locale.", archive_string_conversion_charset_name(lha->sconv)); err = ARCHIVE_WARN; } archive_string_free(&pathname); if (archive_strlen(&linkname) > 0) { if (archive_entry_copy_symlink_l(entry, linkname.s, linkname.length, lha->sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Linkname cannot be converted " "from %s to current locale.", archive_string_conversion_charset_name(lha->sconv)); err = ARCHIVE_WARN; } } else archive_entry_set_symlink(entry, NULL); archive_string_free(&linkname); /* * When a header level is 0, there is a possibility that * a pathname and a symlink has '\' character, a directory * separator in DOS/Windows. So we should convert it to '/'. */ if (p[H_LEVEL_OFFSET] == 0) lha_replace_path_separator(lha, entry); archive_entry_set_mode(entry, lha->mode); archive_entry_set_uid(entry, lha->uid); archive_entry_set_gid(entry, lha->gid); if (archive_strlen(&lha->uname) > 0) archive_entry_set_uname(entry, lha->uname.s); if (archive_strlen(&lha->gname) > 0) archive_entry_set_gname(entry, lha->gname.s); if (lha->setflag & BIRTHTIME_IS_SET) { archive_entry_set_birthtime(entry, lha->birthtime, lha->birthtime_tv_nsec); archive_entry_set_ctime(entry, lha->birthtime, lha->birthtime_tv_nsec); } else { archive_entry_unset_birthtime(entry); archive_entry_unset_ctime(entry); } archive_entry_set_mtime(entry, lha->mtime, lha->mtime_tv_nsec); if (lha->setflag & ATIME_IS_SET) archive_entry_set_atime(entry, lha->atime, lha->atime_tv_nsec); else archive_entry_unset_atime(entry); if (lha->directory || archive_entry_symlink(entry) != NULL) archive_entry_unset_size(entry); else archive_entry_set_size(entry, lha->origsize); /* * Prepare variables used to read a file content. */ lha->entry_bytes_remaining = lha->compsize; lha->entry_offset = 0; lha->entry_crc_calculated = 0; /* * This file does not have a content. */ if (lha->directory || lha->compsize == 0) lha->end_of_entry = 1; sprintf(lha->format_name, "lha -%c%c%c-", lha->method[0], lha->method[1], lha->method[2]); a->archive.archive_format_name = lha->format_name; return (err); } /* * Replace a DOS path separator '\' by a character '/'. * Some multi-byte character set have a character '\' in its second byte. */ static void lha_replace_path_separator(struct lha *lha, struct archive_entry *entry) { const wchar_t *wp; size_t i; if ((wp = archive_entry_pathname_w(entry)) != NULL) { archive_wstrcpy(&(lha->ws), wp); for (i = 0; i < archive_strlen(&(lha->ws)); i++) { if (lha->ws.s[i] == L'\\') lha->ws.s[i] = L'/'; } archive_entry_copy_pathname_w(entry, lha->ws.s); } if ((wp = archive_entry_symlink_w(entry)) != NULL) { archive_wstrcpy(&(lha->ws), wp); for (i = 0; i < archive_strlen(&(lha->ws)); i++) { if (lha->ws.s[i] == L'\\') lha->ws.s[i] = L'/'; } archive_entry_copy_symlink_w(entry, lha->ws.s); } } /* * Header 0 format * * +0 +1 +2 +7 +11 * +---------------+----------+----------------+-------------------+ * |header size(*1)|header sum|compression type|compressed size(*2)| * +---------------+----------+----------------+-------------------+ * <---------------------(*1)----------* * * +11 +15 +17 +19 +20 +21 * +-----------------+---------+---------+--------------+----------------+ * |uncompressed size|time(DOS)|date(DOS)|attribute(DOS)|header level(=0)| * +-----------------+---------+---------+--------------+----------------+ * *--------------------------------(*1)---------------------------------* * * +21 +22 +22+(*3) +22+(*3)+2 +22+(*3)+2+(*4) * +---------------+---------+----------+----------------+------------------+ * |name length(*3)|file name|file CRC16|extra header(*4)| compressed data | * +---------------+---------+----------+----------------+------------------+ * <--(*3)-> <------(*2)------> * *----------------------(*1)--------------------------> * */ #define H0_HEADER_SIZE_OFFSET 0 #define H0_HEADER_SUM_OFFSET 1 #define H0_COMP_SIZE_OFFSET 7 #define H0_ORIG_SIZE_OFFSET 11 #define H0_DOS_TIME_OFFSET 15 #define H0_NAME_LEN_OFFSET 21 #define H0_FILE_NAME_OFFSET 22 #define H0_FIXED_SIZE 24 static int lha_read_file_header_0(struct archive_read *a, struct lha *lha) { const unsigned char *p; int extdsize, namelen; unsigned char headersum, sum_calculated; if ((p = __archive_read_ahead(a, H0_FIXED_SIZE, NULL)) == NULL) return (truncated_error(a)); lha->header_size = p[H0_HEADER_SIZE_OFFSET] + 2; headersum = p[H0_HEADER_SUM_OFFSET]; lha->compsize = archive_le32dec(p + H0_COMP_SIZE_OFFSET); lha->origsize = archive_le32dec(p + H0_ORIG_SIZE_OFFSET); lha->mtime = lha_dos_time(p + H0_DOS_TIME_OFFSET); namelen = p[H0_NAME_LEN_OFFSET]; extdsize = (int)lha->header_size - H0_FIXED_SIZE - namelen; if ((namelen > 221 || extdsize < 0) && extdsize != -2) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid LHa header"); return (ARCHIVE_FATAL); } if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL) return (truncated_error(a)); archive_strncpy(&lha->filename, p + H0_FILE_NAME_OFFSET, namelen); /* When extdsize == -2, A CRC16 value is not present in the header. */ if (extdsize >= 0) { lha->crc = archive_le16dec(p + H0_FILE_NAME_OFFSET + namelen); lha->setflag |= CRC_IS_SET; } sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2); /* Read an extended header */ if (extdsize > 0) { /* This extended data is set by 'LHa for UNIX' only. * Maybe fixed size. */ p += H0_FILE_NAME_OFFSET + namelen + 2; if (p[0] == 'U' && extdsize == 12) { /* p[1] is a minor version. */ lha->mtime = archive_le32dec(&p[2]); lha->mode = archive_le16dec(&p[6]); lha->uid = archive_le16dec(&p[8]); lha->gid = archive_le16dec(&p[10]); lha->setflag |= UNIX_MODE_IS_SET; } } __archive_read_consume(a, lha->header_size); if (sum_calculated != headersum) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "LHa header sum error"); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } /* * Header 1 format * * +0 +1 +2 +7 +11 * +---------------+----------+----------------+-------------+ * |header size(*1)|header sum|compression type|skip size(*2)| * +---------------+----------+----------------+-------------+ * <---------------(*1)----------* * * +11 +15 +17 +19 +20 +21 * +-----------------+---------+---------+--------------+----------------+ * |uncompressed size|time(DOS)|date(DOS)|attribute(DOS)|header level(=1)| * +-----------------+---------+---------+--------------+----------------+ * *-------------------------------(*1)----------------------------------* * * +21 +22 +22+(*3) +22+(*3)+2 +22+(*3)+3 +22+(*3)+3+(*4) * +---------------+---------+----------+-----------+-----------+ * |name length(*3)|file name|file CRC16| creator |padding(*4)| * +---------------+---------+----------+-----------+-----------+ * <--(*3)-> * *----------------------------(*1)----------------------------* * * +22+(*3)+3+(*4) +22+(*3)+3+(*4)+2 +22+(*3)+3+(*4)+2+(*5) * +----------------+---------------------+------------------------+ * |next header size| extended header(*5) | compressed data | * +----------------+---------------------+------------------------+ * *------(*1)-----> <--------------------(*2)--------------------> */ #define H1_HEADER_SIZE_OFFSET 0 #define H1_HEADER_SUM_OFFSET 1 #define H1_COMP_SIZE_OFFSET 7 #define H1_ORIG_SIZE_OFFSET 11 #define H1_DOS_TIME_OFFSET 15 #define H1_NAME_LEN_OFFSET 21 #define H1_FILE_NAME_OFFSET 22 #define H1_FIXED_SIZE 27 static int lha_read_file_header_1(struct archive_read *a, struct lha *lha) { const unsigned char *p; size_t extdsize; int i, err, err2; int namelen, padding; unsigned char headersum, sum_calculated; err = ARCHIVE_OK; if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL) return (truncated_error(a)); lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2; headersum = p[H1_HEADER_SUM_OFFSET]; /* Note: An extended header size is included in a compsize. */ lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET); lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET); lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET); namelen = p[H1_NAME_LEN_OFFSET]; /* Calculate a padding size. The result will be normally 0 only(?) */ padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen; if (namelen > 230 || padding < 0) goto invalid; if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL) return (truncated_error(a)); for (i = 0; i < namelen; i++) { if (p[i + H1_FILE_NAME_OFFSET] == 0xff) goto invalid;/* Invalid filename. */ } archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen); lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen); lha->setflag |= CRC_IS_SET; sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2); /* Consume used bytes but not include `next header size' data * since it will be consumed in lha_read_file_extended_header(). */ __archive_read_consume(a, lha->header_size - 2); /* Read extended headers */ err2 = lha_read_file_extended_header(a, lha, NULL, 2, (size_t)(lha->compsize + 2), &extdsize); if (err2 < ARCHIVE_WARN) return (err2); if (err2 < err) err = err2; /* Get a real compressed file size. */ lha->compsize -= extdsize - 2; if (sum_calculated != headersum) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "LHa header sum error"); return (ARCHIVE_FATAL); } return (err); invalid: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid LHa header"); return (ARCHIVE_FATAL); } /* * Header 2 format * * +0 +2 +7 +11 +15 * +---------------+----------------+-------------------+-----------------+ * |header size(*1)|compression type|compressed size(*2)|uncompressed size| * +---------------+----------------+-------------------+-----------------+ * <--------------------------------(*1)---------------------------------* * * +15 +19 +20 +21 +23 +24 * +-----------------+------------+----------------+----------+-----------+ * |data/time(time_t)| 0x20 fixed |header level(=2)|file CRC16| creator | * +-----------------+------------+----------------+----------+-----------+ * *---------------------------------(*1)---------------------------------* * * +24 +26 +26+(*3) +26+(*3)+(*4) * +----------------+-------------------+-------------+-------------------+ * |next header size|extended header(*3)| padding(*4) | compressed data | * +----------------+-------------------+-------------+-------------------+ * *--------------------------(*1)-------------------> <------(*2)-------> * */ #define H2_HEADER_SIZE_OFFSET 0 #define H2_COMP_SIZE_OFFSET 7 #define H2_ORIG_SIZE_OFFSET 11 #define H2_TIME_OFFSET 15 #define H2_CRC_OFFSET 21 #define H2_FIXED_SIZE 24 static int lha_read_file_header_2(struct archive_read *a, struct lha *lha) { const unsigned char *p; size_t extdsize; int err, padding; uint16_t header_crc; if ((p = __archive_read_ahead(a, H2_FIXED_SIZE, NULL)) == NULL) return (truncated_error(a)); lha->header_size =archive_le16dec(p + H2_HEADER_SIZE_OFFSET); lha->compsize = archive_le32dec(p + H2_COMP_SIZE_OFFSET); lha->origsize = archive_le32dec(p + H2_ORIG_SIZE_OFFSET); lha->mtime = archive_le32dec(p + H2_TIME_OFFSET); lha->crc = archive_le16dec(p + H2_CRC_OFFSET); lha->setflag |= CRC_IS_SET; if (lha->header_size < H2_FIXED_SIZE) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid LHa header size"); return (ARCHIVE_FATAL); } header_crc = lha_crc16(0, p, H2_FIXED_SIZE); __archive_read_consume(a, H2_FIXED_SIZE); /* Read extended headers */ err = lha_read_file_extended_header(a, lha, &header_crc, 2, lha->header_size - H2_FIXED_SIZE, &extdsize); if (err < ARCHIVE_WARN) return (err); /* Calculate a padding size. The result will be normally 0 or 1. */ padding = (int)lha->header_size - (int)(H2_FIXED_SIZE + extdsize); if (padding > 0) { if ((p = __archive_read_ahead(a, padding, NULL)) == NULL) return (truncated_error(a)); header_crc = lha_crc16(header_crc, p, padding); __archive_read_consume(a, padding); } if (header_crc != lha->header_crc) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "LHa header CRC error"); return (ARCHIVE_FATAL); } return (err); } /* * Header 3 format * * +0 +2 +7 +11 +15 * +------------+----------------+-------------------+-----------------+ * | 0x04 fixed |compression type|compressed size(*2)|uncompressed size| * +------------+----------------+-------------------+-----------------+ * <-------------------------------(*1)-------------------------------* * * +15 +19 +20 +21 +23 +24 * +-----------------+------------+----------------+----------+-----------+ * |date/time(time_t)| 0x20 fixed |header level(=3)|file CRC16| creator | * +-----------------+------------+----------------+----------+-----------+ * *--------------------------------(*1)----------------------------------* * * +24 +28 +32 +32+(*3) * +---------------+----------------+-------------------+-----------------+ * |header size(*1)|next header size|extended header(*3)| compressed data | * +---------------+----------------+-------------------+-----------------+ * *------------------------(*1)-----------------------> <------(*2)-----> * */ #define H3_FIELD_LEN_OFFSET 0 #define H3_COMP_SIZE_OFFSET 7 #define H3_ORIG_SIZE_OFFSET 11 #define H3_TIME_OFFSET 15 #define H3_CRC_OFFSET 21 #define H3_HEADER_SIZE_OFFSET 24 #define H3_FIXED_SIZE 28 static int lha_read_file_header_3(struct archive_read *a, struct lha *lha) { const unsigned char *p; size_t extdsize; int err; uint16_t header_crc; if ((p = __archive_read_ahead(a, H3_FIXED_SIZE, NULL)) == NULL) return (truncated_error(a)); if (archive_le16dec(p + H3_FIELD_LEN_OFFSET) != 4) goto invalid; lha->header_size =archive_le32dec(p + H3_HEADER_SIZE_OFFSET); lha->compsize = archive_le32dec(p + H3_COMP_SIZE_OFFSET); lha->origsize = archive_le32dec(p + H3_ORIG_SIZE_OFFSET); lha->mtime = archive_le32dec(p + H3_TIME_OFFSET); lha->crc = archive_le16dec(p + H3_CRC_OFFSET); lha->setflag |= CRC_IS_SET; if (lha->header_size < H3_FIXED_SIZE + 4) goto invalid; header_crc = lha_crc16(0, p, H3_FIXED_SIZE); __archive_read_consume(a, H3_FIXED_SIZE); /* Read extended headers */ err = lha_read_file_extended_header(a, lha, &header_crc, 4, lha->header_size - H3_FIXED_SIZE, &extdsize); if (err < ARCHIVE_WARN) return (err); if (header_crc != lha->header_crc) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "LHa header CRC error"); return (ARCHIVE_FATAL); } return (err); invalid: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid LHa header"); return (ARCHIVE_FATAL); } /* * Extended header format * * +0 +2 +3 -- used in header 1 and 2 * +0 +4 +5 -- used in header 3 * +--------------+---------+-------------------+--------------+-- * |ex-header size|header id| data |ex-header size| ....... * +--------------+---------+-------------------+--------------+-- * <-------------( ex-header size)------------> <-- next extended header --* * * If the ex-header size is zero, it is the make of the end of extended * headers. * */ static int lha_read_file_extended_header(struct archive_read *a, struct lha *lha, uint16_t *crc, int sizefield_length, size_t limitsize, size_t *total_size) { const void *h; const unsigned char *extdheader; size_t extdsize; size_t datasize; unsigned int i; unsigned char extdtype; #define EXT_HEADER_CRC 0x00 /* Header CRC and information*/ #define EXT_FILENAME 0x01 /* Filename */ #define EXT_DIRECTORY 0x02 /* Directory name */ #define EXT_DOS_ATTR 0x40 /* MS-DOS attribute */ #define EXT_TIMESTAMP 0x41 /* Windows time stamp */ #define EXT_FILESIZE 0x42 /* Large file size */ #define EXT_TIMEZONE 0x43 /* Time zone */ #define EXT_UTF16_FILENAME 0x44 /* UTF-16 filename */ #define EXT_UTF16_DIRECTORY 0x45 /* UTF-16 directory name */ #define EXT_CODEPAGE 0x46 /* Codepage */ #define EXT_UNIX_MODE 0x50 /* File permission */ #define EXT_UNIX_GID_UID 0x51 /* gid,uid */ #define EXT_UNIX_GNAME 0x52 /* Group name */ #define EXT_UNIX_UNAME 0x53 /* User name */ #define EXT_UNIX_MTIME 0x54 /* Modified time */ #define EXT_OS2_NEW_ATTR 0x7f /* new attribute(OS/2 only) */ #define EXT_NEW_ATTR 0xff /* new attribute */ *total_size = sizefield_length; for (;;) { /* Read an extended header size. */ if ((h = __archive_read_ahead(a, sizefield_length, NULL)) == NULL) return (truncated_error(a)); /* Check if the size is the zero indicates the end of the * extended header. */ if (sizefield_length == sizeof(uint16_t)) extdsize = archive_le16dec(h); else extdsize = archive_le32dec(h); if (extdsize == 0) { /* End of extended header */ if (crc != NULL) *crc = lha_crc16(*crc, h, sizefield_length); __archive_read_consume(a, sizefield_length); return (ARCHIVE_OK); } /* Sanity check to the extended header size. */ if (((uint64_t)*total_size + extdsize) > (uint64_t)limitsize || extdsize <= (size_t)sizefield_length) goto invalid; /* Read the extended header. */ if ((h = __archive_read_ahead(a, extdsize, NULL)) == NULL) return (truncated_error(a)); *total_size += extdsize; extdheader = (const unsigned char *)h; /* Get the extended header type. */ extdtype = extdheader[sizefield_length]; /* Calculate an extended data size. */ datasize = extdsize - (1 + sizefield_length); /* Skip an extended header size field and type field. */ extdheader += sizefield_length + 1; if (crc != NULL && extdtype != EXT_HEADER_CRC) *crc = lha_crc16(*crc, h, extdsize); switch (extdtype) { case EXT_HEADER_CRC: /* We only use a header CRC. Following data will not * be used. */ if (datasize >= 2) { lha->header_crc = archive_le16dec(extdheader); if (crc != NULL) { static const char zeros[2] = {0, 0}; *crc = lha_crc16(*crc, h, extdsize - datasize); /* CRC value itself as zero */ *crc = lha_crc16(*crc, zeros, 2); *crc = lha_crc16(*crc, extdheader+2, datasize - 2); } } break; case EXT_FILENAME: if (datasize == 0) { /* maybe directory header */ archive_string_empty(&lha->filename); break; } if (extdheader[0] == '\0') goto invalid; archive_strncpy(&lha->filename, (const char *)extdheader, datasize); break; case EXT_DIRECTORY: if (datasize == 0 || extdheader[0] == '\0') /* no directory name data. exit this case. */ goto invalid; archive_strncpy(&lha->dirname, (const char *)extdheader, datasize); /* * Convert directory delimiter from 0xFF * to '/' for local system. */ for (i = 0; i < lha->dirname.length; i++) { if ((unsigned char)lha->dirname.s[i] == 0xFF) lha->dirname.s[i] = '/'; } /* Is last character directory separator? */ if (lha->dirname.s[lha->dirname.length-1] != '/') /* invalid directory data */ goto invalid; break; case EXT_DOS_ATTR: if (datasize == 2) lha->dos_attr = (unsigned char) (archive_le16dec(extdheader) & 0xff); break; case EXT_TIMESTAMP: if (datasize == (sizeof(uint64_t) * 3)) { lha->birthtime = lha_win_time( archive_le64dec(extdheader), &lha->birthtime_tv_nsec); extdheader += sizeof(uint64_t); lha->mtime = lha_win_time( archive_le64dec(extdheader), &lha->mtime_tv_nsec); extdheader += sizeof(uint64_t); lha->atime = lha_win_time( archive_le64dec(extdheader), &lha->atime_tv_nsec); lha->setflag |= BIRTHTIME_IS_SET | ATIME_IS_SET; } break; case EXT_FILESIZE: if (datasize == sizeof(uint64_t) * 2) { lha->compsize = archive_le64dec(extdheader); extdheader += sizeof(uint64_t); lha->origsize = archive_le64dec(extdheader); } break; case EXT_CODEPAGE: /* Get an archived filename charset from codepage. * This overwrites the charset specified by * hdrcharset option. */ if (datasize == sizeof(uint32_t)) { struct archive_string cp; const char *charset; archive_string_init(&cp); switch (archive_le32dec(extdheader)) { case 65001: /* UTF-8 */ charset = "UTF-8"; break; default: archive_string_sprintf(&cp, "CP%d", (int)archive_le32dec(extdheader)); charset = cp.s; break; } lha->sconv = archive_string_conversion_from_charset( &(a->archive), charset, 1); archive_string_free(&cp); if (lha->sconv == NULL) return (ARCHIVE_FATAL); } break; case EXT_UNIX_MODE: if (datasize == sizeof(uint16_t)) { lha->mode = archive_le16dec(extdheader); lha->setflag |= UNIX_MODE_IS_SET; } break; case EXT_UNIX_GID_UID: if (datasize == (sizeof(uint16_t) * 2)) { lha->gid = archive_le16dec(extdheader); lha->uid = archive_le16dec(extdheader+2); } break; case EXT_UNIX_GNAME: if (datasize > 0) archive_strncpy(&lha->gname, (const char *)extdheader, datasize); break; case EXT_UNIX_UNAME: if (datasize > 0) archive_strncpy(&lha->uname, (const char *)extdheader, datasize); break; case EXT_UNIX_MTIME: if (datasize == sizeof(uint32_t)) lha->mtime = archive_le32dec(extdheader); break; case EXT_OS2_NEW_ATTR: /* This extended header is OS/2 depend. */ if (datasize == 16) { lha->dos_attr = (unsigned char) (archive_le16dec(extdheader) & 0xff); lha->mode = archive_le16dec(extdheader+2); lha->gid = archive_le16dec(extdheader+4); lha->uid = archive_le16dec(extdheader+6); lha->birthtime = archive_le32dec(extdheader+8); lha->atime = archive_le32dec(extdheader+12); lha->setflag |= UNIX_MODE_IS_SET | BIRTHTIME_IS_SET | ATIME_IS_SET; } break; case EXT_NEW_ATTR: if (datasize == 20) { lha->mode = (mode_t)archive_le32dec(extdheader); lha->gid = archive_le32dec(extdheader+4); lha->uid = archive_le32dec(extdheader+8); lha->birthtime = archive_le32dec(extdheader+12); lha->atime = archive_le32dec(extdheader+16); lha->setflag |= UNIX_MODE_IS_SET | BIRTHTIME_IS_SET | ATIME_IS_SET; } break; case EXT_TIMEZONE: /* Not supported */ case EXT_UTF16_FILENAME: /* Not supported */ case EXT_UTF16_DIRECTORY: /* Not supported */ default: break; } __archive_read_consume(a, extdsize); } invalid: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid extended LHa header"); return (ARCHIVE_FATAL); } static int lha_end_of_entry(struct archive_read *a) { struct lha *lha = (struct lha *)(a->format->data); int r = ARCHIVE_EOF; if (!lha->end_of_entry_cleanup) { if ((lha->setflag & CRC_IS_SET) && lha->crc != lha->entry_crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "LHa data CRC error"); r = ARCHIVE_WARN; } /* End-of-entry cleanup done. */ lha->end_of_entry_cleanup = 1; } return (r); } static int archive_read_format_lha_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct lha *lha = (struct lha *)(a->format->data); int r; if (lha->entry_unconsumed) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, lha->entry_unconsumed); lha->entry_unconsumed = 0; } if (lha->end_of_entry) { *offset = lha->entry_offset; *size = 0; *buff = NULL; return (lha_end_of_entry(a)); } if (lha->entry_is_compressed) r = lha_read_data_lzh(a, buff, size, offset); else /* No compression. */ r = lha_read_data_none(a, buff, size, offset); return (r); } /* * Read a file content in no compression. * * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets * lha->end_of_entry if it consumes all of the data. */ static int lha_read_data_none(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct lha *lha = (struct lha *)(a->format->data); ssize_t bytes_avail; if (lha->entry_bytes_remaining == 0) { *buff = NULL; *size = 0; *offset = lha->entry_offset; lha->end_of_entry = 1; return (ARCHIVE_OK); } /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ *buff = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated LHa file data"); return (ARCHIVE_FATAL); } if (bytes_avail > lha->entry_bytes_remaining) bytes_avail = (ssize_t)lha->entry_bytes_remaining; lha->entry_crc_calculated = lha_crc16(lha->entry_crc_calculated, *buff, bytes_avail); *size = bytes_avail; *offset = lha->entry_offset; lha->entry_offset += bytes_avail; lha->entry_bytes_remaining -= bytes_avail; if (lha->entry_bytes_remaining == 0) lha->end_of_entry = 1; lha->entry_unconsumed = bytes_avail; return (ARCHIVE_OK); } /* * Read a file content in LZHUFF encoding. * * Returns ARCHIVE_OK if successful, returns ARCHIVE_WARN if compression is * unsupported, ARCHIVE_FATAL otherwise, sets lha->end_of_entry if it consumes * all of the data. */ static int lha_read_data_lzh(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct lha *lha = (struct lha *)(a->format->data); ssize_t bytes_avail; int r; /* If we haven't yet read any data, initialize the decompressor. */ if (!lha->decompress_init) { r = lzh_decode_init(&(lha->strm), lha->method); switch (r) { case ARCHIVE_OK: break; case ARCHIVE_FAILED: /* Unsupported compression. */ *buff = NULL; *size = 0; *offset = 0; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported lzh compression method -%c%c%c-", lha->method[0], lha->method[1], lha->method[2]); /* We know compressed size; just skip it. */ archive_read_format_lha_read_data_skip(a); return (ARCHIVE_WARN); default: archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory " "for lzh decompression"); return (ARCHIVE_FATAL); } /* We've initialized decompression for this stream. */ lha->decompress_init = 1; lha->strm.avail_out = 0; lha->strm.total_out = 0; } /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ lha->strm.next_in = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated LHa file body"); return (ARCHIVE_FATAL); } if (bytes_avail > lha->entry_bytes_remaining) bytes_avail = (ssize_t)lha->entry_bytes_remaining; lha->strm.avail_in = (int)bytes_avail; lha->strm.total_in = 0; lha->strm.avail_out = 0; r = lzh_decode(&(lha->strm), bytes_avail == lha->entry_bytes_remaining); switch (r) { case ARCHIVE_OK: break; case ARCHIVE_EOF: lha->end_of_entry = 1; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Bad lzh data"); return (ARCHIVE_FAILED); } lha->entry_unconsumed = lha->strm.total_in; lha->entry_bytes_remaining -= lha->strm.total_in; if (lha->strm.avail_out) { *offset = lha->entry_offset; *size = lha->strm.avail_out; *buff = lha->strm.ref_ptr; lha->entry_crc_calculated = lha_crc16(lha->entry_crc_calculated, *buff, *size); lha->entry_offset += *size; } else { *offset = lha->entry_offset; *size = 0; *buff = NULL; if (lha->end_of_entry) return (lha_end_of_entry(a)); } return (ARCHIVE_OK); } /* * Skip a file content. */ static int archive_read_format_lha_read_data_skip(struct archive_read *a) { struct lha *lha; int64_t bytes_skipped; lha = (struct lha *)(a->format->data); if (lha->entry_unconsumed) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, lha->entry_unconsumed); lha->entry_unconsumed = 0; } /* if we've already read to end of data, we're done. */ if (lha->end_of_entry_cleanup) return (ARCHIVE_OK); /* * If the length is at the beginning, we can skip the * compressed data much more quickly. */ bytes_skipped = __archive_read_consume(a, lha->entry_bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); /* This entry is finished and done. */ lha->end_of_entry_cleanup = lha->end_of_entry = 1; return (ARCHIVE_OK); } static int archive_read_format_lha_cleanup(struct archive_read *a) { struct lha *lha = (struct lha *)(a->format->data); lzh_decode_free(&(lha->strm)); archive_string_free(&(lha->dirname)); archive_string_free(&(lha->filename)); archive_string_free(&(lha->uname)); archive_string_free(&(lha->gname)); archive_wstring_free(&(lha->ws)); free(lha); (a->format->data) = NULL; return (ARCHIVE_OK); } /* * 'LHa for UNIX' utility has archived a symbolic-link name after * a pathname with '|' character. * This function extracts the symbolic-link name from the pathname. * * example. * 1. a symbolic-name is 'aaa/bb/cc' * 2. a filename is 'xxx/bbb' * then a archived pathname is 'xxx/bbb|aaa/bb/cc' */ static int lha_parse_linkname(struct archive_string *linkname, struct archive_string *pathname) { char * linkptr; size_t symlen; linkptr = strchr(pathname->s, '|'); if (linkptr != NULL) { symlen = strlen(linkptr + 1); archive_strncpy(linkname, linkptr+1, symlen); *linkptr = 0; pathname->length = strlen(pathname->s); return (1); } return (0); } /* Convert an MSDOS-style date/time into Unix-style time. */ static time_t lha_dos_time(const unsigned char *p) { int msTime, msDate; struct tm ts; msTime = archive_le16dec(p); msDate = archive_le16dec(p+2); memset(&ts, 0, sizeof(ts)); ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */ ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */ ts.tm_mday = msDate & 0x1f; /* Day of month. */ ts.tm_hour = (msTime >> 11) & 0x1f; ts.tm_min = (msTime >> 5) & 0x3f; ts.tm_sec = (msTime << 1) & 0x3e; ts.tm_isdst = -1; return (mktime(&ts)); } /* Convert an MS-Windows-style date/time into Unix-style time. */ static time_t lha_win_time(uint64_t wintime, long *ns) { #define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000) if (wintime >= EPOC_TIME) { wintime -= EPOC_TIME; /* 1970-01-01 00:00:00 (UTC) */ if (ns != NULL) *ns = (long)(wintime % 10000000) * 100; return (wintime / 10000000); } else { if (ns != NULL) *ns = 0; return (0); } } static unsigned char lha_calcsum(unsigned char sum, const void *pp, int offset, size_t size) { unsigned char const *p = (unsigned char const *)pp; p += offset; for (;size > 0; --size) sum += *p++; return (sum); } static uint16_t crc16tbl[2][256]; static void lha_crc16_init(void) { unsigned int i; static int crc16init = 0; if (crc16init) return; crc16init = 1; for (i = 0; i < 256; i++) { unsigned int j; uint16_t crc = (uint16_t)i; for (j = 8; j; j--) crc = (crc >> 1) ^ ((crc & 1) * 0xA001); crc16tbl[0][i] = crc; } for (i = 0; i < 256; i++) { crc16tbl[1][i] = (crc16tbl[0][i] >> 8) ^ crc16tbl[0][crc16tbl[0][i] & 0xff]; } } static uint16_t lha_crc16(uint16_t crc, const void *pp, size_t len) { const unsigned char *p = (const unsigned char *)pp; const uint16_t *buff; const union { uint32_t i; char c[4]; } u = { 0x01020304 }; if (len == 0) return crc; /* Process unaligned address. */ if (((uintptr_t)p) & (uintptr_t)0x1) { crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff]; len--; } buff = (const uint16_t *)p; /* * Modern C compiler such as GCC does not unroll automatically yet * without unrolling pragma, and Clang is so. So we should * unroll this loop for its performance. */ for (;len >= 8; len -= 8) { /* This if statement expects compiler optimization will * remove the statement which will not be executed. */ #undef bswap16 #if defined(_MSC_VER) && _MSC_VER >= 1400 /* Visual Studio */ # define bswap16(x) _byteswap_ushort(x) #elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ > 4) /* GCC 4.8 and later has __builtin_bswap16() */ # define bswap16(x) __builtin_bswap16(x) #elif defined(__clang__) /* All clang versions have __builtin_bswap16() */ # define bswap16(x) __builtin_bswap16(x) #else # define bswap16(x) ((((x) >> 8) & 0xff) | ((x) << 8)) #endif #define CRC16W do { \ if(u.c[0] == 1) { /* Big endian */ \ crc ^= bswap16(*buff); buff++; \ } else \ crc ^= *buff++; \ crc = crc16tbl[1][crc & 0xff] ^ crc16tbl[0][crc >> 8];\ } while (0) CRC16W; CRC16W; CRC16W; CRC16W; #undef CRC16W #undef bswap16 } p = (const unsigned char *)buff; for (;len; len--) { crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff]; } return crc; } /* * Initialize LZHUF decoder. * * Returns ARCHIVE_OK if initialization was successful. * Returns ARCHIVE_FAILED if method is unsupported. * Returns ARCHIVE_FATAL if initialization failed; memory allocation * error occurred. */ static int lzh_decode_init(struct lzh_stream *strm, const char *method) { struct lzh_dec *ds; int w_bits, w_size; if (strm->ds == NULL) { strm->ds = calloc(1, sizeof(*strm->ds)); if (strm->ds == NULL) return (ARCHIVE_FATAL); } ds = strm->ds; ds->error = ARCHIVE_FAILED; if (method == NULL || method[0] != 'l' || method[1] != 'h') return (ARCHIVE_FAILED); switch (method[2]) { case '5': w_bits = 13;/* 8KiB for window */ break; case '6': w_bits = 15;/* 32KiB for window */ break; case '7': w_bits = 16;/* 64KiB for window */ break; default: return (ARCHIVE_FAILED);/* Not supported. */ } ds->error = ARCHIVE_FATAL; /* Expand a window size up to 128 KiB for decompressing process * performance whatever its original window size is. */ ds->w_size = 1U << 17; ds->w_mask = ds->w_size -1; if (ds->w_buff == NULL) { ds->w_buff = malloc(ds->w_size); if (ds->w_buff == NULL) return (ARCHIVE_FATAL); } w_size = 1U << w_bits; memset(ds->w_buff + ds->w_size - w_size, 0x20, w_size); ds->w_pos = 0; ds->state = 0; ds->pos_pt_len_size = w_bits + 1; ds->pos_pt_len_bits = (w_bits == 15 || w_bits == 16)? 5: 4; ds->literal_pt_len_size = PT_BITLEN_SIZE; ds->literal_pt_len_bits = 5; ds->br.cache_buffer = 0; ds->br.cache_avail = 0; if (lzh_huffman_init(&(ds->lt), LT_BITLEN_SIZE, 16) != ARCHIVE_OK) return (ARCHIVE_FATAL); ds->lt.len_bits = 9; if (lzh_huffman_init(&(ds->pt), PT_BITLEN_SIZE, 16) != ARCHIVE_OK) return (ARCHIVE_FATAL); ds->error = 0; return (ARCHIVE_OK); } /* * Release LZHUF decoder. */ static void lzh_decode_free(struct lzh_stream *strm) { if (strm->ds == NULL) return; free(strm->ds->w_buff); lzh_huffman_free(&(strm->ds->lt)); lzh_huffman_free(&(strm->ds->pt)); free(strm->ds); strm->ds = NULL; } /* * Bit stream reader. */ /* Check that the cache buffer has enough bits. */ #define lzh_br_has(br, n) ((br)->cache_avail >= n) /* Get compressed data by bit. */ #define lzh_br_bits(br, n) \ (((uint16_t)((br)->cache_buffer >> \ ((br)->cache_avail - (n)))) & cache_masks[n]) #define lzh_br_bits_forced(br, n) \ (((uint16_t)((br)->cache_buffer << \ ((n) - (br)->cache_avail))) & cache_masks[n]) /* Read ahead to make sure the cache buffer has enough compressed data we * will use. * True : completed, there is enough data in the cache buffer. * False : we met that strm->next_in is empty, we have to get following * bytes. */ #define lzh_br_read_ahead_0(strm, br, n) \ (lzh_br_has(br, (n)) || lzh_br_fillup(strm, br)) /* True : the cache buffer has some bits as much as we need. * False : there are no enough bits in the cache buffer to be used, * we have to get following bytes if we could. */ #define lzh_br_read_ahead(strm, br, n) \ (lzh_br_read_ahead_0((strm), (br), (n)) || lzh_br_has((br), (n))) /* Notify how many bits we consumed. */ #define lzh_br_consume(br, n) ((br)->cache_avail -= (n)) #define lzh_br_unconsume(br, n) ((br)->cache_avail += (n)) static const uint16_t cache_masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF }; /* * Shift away used bits in the cache data and fill it up with following bits. * Call this when cache buffer does not have enough bits you need. * * Returns 1 if the cache buffer is full. * Returns 0 if the cache buffer is not full; input buffer is empty. */ static int lzh_br_fillup(struct lzh_stream *strm, struct lzh_br *br) { int n = CACHE_BITS - br->cache_avail; for (;;) { const int x = n >> 3; if (strm->avail_in >= x) { switch (x) { case 8: br->cache_buffer = ((uint64_t)strm->next_in[0]) << 56 | ((uint64_t)strm->next_in[1]) << 48 | ((uint64_t)strm->next_in[2]) << 40 | ((uint64_t)strm->next_in[3]) << 32 | ((uint32_t)strm->next_in[4]) << 24 | ((uint32_t)strm->next_in[5]) << 16 | ((uint32_t)strm->next_in[6]) << 8 | (uint32_t)strm->next_in[7]; strm->next_in += 8; strm->avail_in -= 8; br->cache_avail += 8 * 8; return (1); case 7: br->cache_buffer = (br->cache_buffer << 56) | ((uint64_t)strm->next_in[0]) << 48 | ((uint64_t)strm->next_in[1]) << 40 | ((uint64_t)strm->next_in[2]) << 32 | ((uint32_t)strm->next_in[3]) << 24 | ((uint32_t)strm->next_in[4]) << 16 | ((uint32_t)strm->next_in[5]) << 8 | (uint32_t)strm->next_in[6]; strm->next_in += 7; strm->avail_in -= 7; br->cache_avail += 7 * 8; return (1); case 6: br->cache_buffer = (br->cache_buffer << 48) | ((uint64_t)strm->next_in[0]) << 40 | ((uint64_t)strm->next_in[1]) << 32 | ((uint32_t)strm->next_in[2]) << 24 | ((uint32_t)strm->next_in[3]) << 16 | ((uint32_t)strm->next_in[4]) << 8 | (uint32_t)strm->next_in[5]; strm->next_in += 6; strm->avail_in -= 6; br->cache_avail += 6 * 8; return (1); case 0: /* We have enough compressed data in * the cache buffer.*/ return (1); default: break; } } if (strm->avail_in == 0) { /* There is not enough compressed data to fill up the * cache buffer. */ return (0); } br->cache_buffer = (br->cache_buffer << 8) | *strm->next_in++; strm->avail_in--; br->cache_avail += 8; n -= 8; } } /* * Decode LZHUF. * * 1. Returns ARCHIVE_OK if output buffer or input buffer are empty. * Please set available buffer and call this function again. * 2. Returns ARCHIVE_EOF if decompression has been completed. * 3. Returns ARCHIVE_FAILED if an error occurred; compressed data * is broken or you do not set 'last' flag properly. * 4. 'last' flag is very important, you must set 1 to the flag if there * is no input data. The lha compressed data format does not provide how * to know the compressed data is really finished. * Note: lha command utility check if the total size of output bytes is * reached the uncompressed size recorded in its header. it does not mind * that the decoding process is properly finished. * GNU ZIP can decompress another compressed file made by SCO LZH compress. * it handles EOF as null to fill read buffer with zero until the decoding * process meet 2 bytes of zeros at reading a size of a next chunk, so the * zeros are treated as the mark of the end of the data although the zeros * is dummy, not the file data. */ static int lzh_read_blocks(struct lzh_stream *, int); static int lzh_decode_blocks(struct lzh_stream *, int); #define ST_RD_BLOCK 0 #define ST_RD_PT_1 1 #define ST_RD_PT_2 2 #define ST_RD_PT_3 3 #define ST_RD_PT_4 4 #define ST_RD_LITERAL_1 5 #define ST_RD_LITERAL_2 6 #define ST_RD_LITERAL_3 7 #define ST_RD_POS_DATA_1 8 #define ST_GET_LITERAL 9 #define ST_GET_POS_1 10 #define ST_GET_POS_2 11 #define ST_COPY_DATA 12 static int lzh_decode(struct lzh_stream *strm, int last) { struct lzh_dec *ds = strm->ds; int avail_in; int r; if (ds->error) return (ds->error); avail_in = strm->avail_in; do { if (ds->state < ST_GET_LITERAL) r = lzh_read_blocks(strm, last); else r = lzh_decode_blocks(strm, last); } while (r == 100); strm->total_in += avail_in - strm->avail_in; return (r); } static void lzh_emit_window(struct lzh_stream *strm, size_t s) { strm->ref_ptr = strm->ds->w_buff; strm->avail_out = (int)s; strm->total_out += s; } static int lzh_read_blocks(struct lzh_stream *strm, int last) { struct lzh_dec *ds = strm->ds; struct lzh_br *br = &(ds->br); int c = 0, i; unsigned rbits; for (;;) { switch (ds->state) { case ST_RD_BLOCK: /* * Read a block number indicates how many blocks * we will handle. The block is composed of a * literal and a match, sometimes a literal only * in particular, there are no reference data at * the beginning of the decompression. */ if (!lzh_br_read_ahead_0(strm, br, 16)) { if (!last) /* We need following data. */ return (ARCHIVE_OK); if (lzh_br_has(br, 8)) { /* * It seems there are extra bits. * 1. Compressed data is broken. * 2. `last' flag does not properly * set. */ goto failed; } if (ds->w_pos > 0) { lzh_emit_window(strm, ds->w_pos); ds->w_pos = 0; return (ARCHIVE_OK); } /* End of compressed data; we have completely * handled all compressed data. */ return (ARCHIVE_EOF); } ds->blocks_avail = lzh_br_bits(br, 16); if (ds->blocks_avail == 0) goto failed; lzh_br_consume(br, 16); /* * Read a literal table compressed in huffman * coding. */ ds->pt.len_size = ds->literal_pt_len_size; ds->pt.len_bits = ds->literal_pt_len_bits; ds->reading_position = 0; /* FALL THROUGH */ case ST_RD_PT_1: /* Note: ST_RD_PT_1, ST_RD_PT_2 and ST_RD_PT_4 are * used in reading both a literal table and a * position table. */ if (!lzh_br_read_ahead(strm, br, ds->pt.len_bits)) { if (last) goto failed;/* Truncated data. */ ds->state = ST_RD_PT_1; return (ARCHIVE_OK); } ds->pt.len_avail = lzh_br_bits(br, ds->pt.len_bits); lzh_br_consume(br, ds->pt.len_bits); /* FALL THROUGH */ case ST_RD_PT_2: if (ds->pt.len_avail == 0) { /* There is no bitlen. */ if (!lzh_br_read_ahead(strm, br, ds->pt.len_bits)) { if (last) goto failed;/* Truncated data.*/ ds->state = ST_RD_PT_2; return (ARCHIVE_OK); } if (!lzh_make_fake_table(&(ds->pt), lzh_br_bits(br, ds->pt.len_bits))) goto failed;/* Invalid data. */ lzh_br_consume(br, ds->pt.len_bits); if (ds->reading_position) ds->state = ST_GET_LITERAL; else ds->state = ST_RD_LITERAL_1; break; } else if (ds->pt.len_avail > ds->pt.len_size) goto failed;/* Invalid data. */ ds->loop = 0; memset(ds->pt.freq, 0, sizeof(ds->pt.freq)); if (ds->pt.len_avail < 3 || ds->pt.len_size == ds->pos_pt_len_size) { ds->state = ST_RD_PT_4; break; } /* FALL THROUGH */ case ST_RD_PT_3: ds->loop = lzh_read_pt_bitlen(strm, ds->loop, 3); if (ds->loop < 3) { if (ds->loop < 0 || last) goto failed;/* Invalid data. */ /* Not completed, get following data. */ ds->state = ST_RD_PT_3; return (ARCHIVE_OK); } /* There are some null in bitlen of the literal. */ if (!lzh_br_read_ahead(strm, br, 2)) { if (last) goto failed;/* Truncated data. */ ds->state = ST_RD_PT_3; return (ARCHIVE_OK); } c = lzh_br_bits(br, 2); lzh_br_consume(br, 2); if (c > ds->pt.len_avail - 3) goto failed;/* Invalid data. */ for (i = 3; c-- > 0 ;) ds->pt.bitlen[i++] = 0; ds->loop = i; /* FALL THROUGH */ case ST_RD_PT_4: ds->loop = lzh_read_pt_bitlen(strm, ds->loop, ds->pt.len_avail); if (ds->loop < ds->pt.len_avail) { if (ds->loop < 0 || last) goto failed;/* Invalid data. */ /* Not completed, get following data. */ ds->state = ST_RD_PT_4; return (ARCHIVE_OK); } if (!lzh_make_huffman_table(&(ds->pt))) goto failed;/* Invalid data */ if (ds->reading_position) { ds->state = ST_GET_LITERAL; break; } /* FALL THROUGH */ case ST_RD_LITERAL_1: if (!lzh_br_read_ahead(strm, br, ds->lt.len_bits)) { if (last) goto failed;/* Truncated data. */ ds->state = ST_RD_LITERAL_1; return (ARCHIVE_OK); } ds->lt.len_avail = lzh_br_bits(br, ds->lt.len_bits); lzh_br_consume(br, ds->lt.len_bits); /* FALL THROUGH */ case ST_RD_LITERAL_2: if (ds->lt.len_avail == 0) { /* There is no bitlen. */ if (!lzh_br_read_ahead(strm, br, ds->lt.len_bits)) { if (last) goto failed;/* Truncated data.*/ ds->state = ST_RD_LITERAL_2; return (ARCHIVE_OK); } if (!lzh_make_fake_table(&(ds->lt), lzh_br_bits(br, ds->lt.len_bits))) goto failed;/* Invalid data */ lzh_br_consume(br, ds->lt.len_bits); ds->state = ST_RD_POS_DATA_1; break; } else if (ds->lt.len_avail > ds->lt.len_size) goto failed;/* Invalid data */ ds->loop = 0; memset(ds->lt.freq, 0, sizeof(ds->lt.freq)); /* FALL THROUGH */ case ST_RD_LITERAL_3: i = ds->loop; while (i < ds->lt.len_avail) { if (!lzh_br_read_ahead(strm, br, ds->pt.max_bits)) { if (last) goto failed;/* Truncated data.*/ ds->loop = i; ds->state = ST_RD_LITERAL_3; return (ARCHIVE_OK); } rbits = lzh_br_bits(br, ds->pt.max_bits); c = lzh_decode_huffman(&(ds->pt), rbits); if (c > 2) { /* Note: 'c' will never be more than * eighteen since it's limited by * PT_BITLEN_SIZE, which is being set * to ds->pt.len_size through * ds->literal_pt_len_size. */ lzh_br_consume(br, ds->pt.bitlen[c]); c -= 2; ds->lt.freq[c]++; ds->lt.bitlen[i++] = c; } else if (c == 0) { lzh_br_consume(br, ds->pt.bitlen[c]); ds->lt.bitlen[i++] = 0; } else { /* c == 1 or c == 2 */ int n = (c == 1)?4:9; if (!lzh_br_read_ahead(strm, br, ds->pt.bitlen[c] + n)) { if (last) /* Truncated data. */ goto failed; ds->loop = i; ds->state = ST_RD_LITERAL_3; return (ARCHIVE_OK); } lzh_br_consume(br, ds->pt.bitlen[c]); c = lzh_br_bits(br, n); lzh_br_consume(br, n); c += (n == 4)?3:20; if (i + c > ds->lt.len_avail) goto failed;/* Invalid data */ memset(&(ds->lt.bitlen[i]), 0, c); i += c; } } if (i > ds->lt.len_avail || !lzh_make_huffman_table(&(ds->lt))) goto failed;/* Invalid data */ /* FALL THROUGH */ case ST_RD_POS_DATA_1: /* * Read a position table compressed in huffman * coding. */ ds->pt.len_size = ds->pos_pt_len_size; ds->pt.len_bits = ds->pos_pt_len_bits; ds->reading_position = 1; ds->state = ST_RD_PT_1; break; case ST_GET_LITERAL: return (100); } } failed: return (ds->error = ARCHIVE_FAILED); } static int lzh_decode_blocks(struct lzh_stream *strm, int last) { struct lzh_dec *ds = strm->ds; struct lzh_br bre = ds->br; struct huffman *lt = &(ds->lt); struct huffman *pt = &(ds->pt); unsigned char *w_buff = ds->w_buff; unsigned char *lt_bitlen = lt->bitlen; unsigned char *pt_bitlen = pt->bitlen; int blocks_avail = ds->blocks_avail, c = 0; int copy_len = ds->copy_len, copy_pos = ds->copy_pos; int w_pos = ds->w_pos, w_mask = ds->w_mask, w_size = ds->w_size; int lt_max_bits = lt->max_bits, pt_max_bits = pt->max_bits; int state = ds->state; for (;;) { switch (state) { case ST_GET_LITERAL: for (;;) { if (blocks_avail == 0) { /* We have decoded all blocks. * Let's handle next blocks. */ ds->state = ST_RD_BLOCK; ds->br = bre; ds->blocks_avail = 0; ds->w_pos = w_pos; ds->copy_pos = 0; return (100); } /* lzh_br_read_ahead() always try to fill the * cache buffer up. In specific situation we * are close to the end of the data, the cache * buffer will not be full and thus we have to * determine if the cache buffer has some bits * as much as we need after lzh_br_read_ahead() * failed. */ if (!lzh_br_read_ahead(strm, &bre, lt_max_bits)) { if (!last) goto next_data; /* Remaining bits are less than * maximum bits(lt.max_bits) but maybe * it still remains as much as we need, * so we should try to use it with * dummy bits. */ c = lzh_decode_huffman(lt, lzh_br_bits_forced(&bre, lt_max_bits)); lzh_br_consume(&bre, lt_bitlen[c]); if (!lzh_br_has(&bre, 0)) goto failed;/* Over read. */ } else { c = lzh_decode_huffman(lt, lzh_br_bits(&bre, lt_max_bits)); lzh_br_consume(&bre, lt_bitlen[c]); } blocks_avail--; if (c > UCHAR_MAX) /* Current block is a match data. */ break; /* * 'c' is exactly a literal code. */ /* Save a decoded code to reference it * afterward. */ w_buff[w_pos] = c; if (++w_pos >= w_size) { w_pos = 0; lzh_emit_window(strm, w_size); goto next_data; } } /* 'c' is the length of a match pattern we have * already extracted, which has be stored in * window(ds->w_buff). */ copy_len = c - (UCHAR_MAX + 1) + MINMATCH; /* FALL THROUGH */ case ST_GET_POS_1: /* * Get a reference position. */ if (!lzh_br_read_ahead(strm, &bre, pt_max_bits)) { if (!last) { state = ST_GET_POS_1; ds->copy_len = copy_len; goto next_data; } copy_pos = lzh_decode_huffman(pt, lzh_br_bits_forced(&bre, pt_max_bits)); lzh_br_consume(&bre, pt_bitlen[copy_pos]); if (!lzh_br_has(&bre, 0)) goto failed;/* Over read. */ } else { copy_pos = lzh_decode_huffman(pt, lzh_br_bits(&bre, pt_max_bits)); lzh_br_consume(&bre, pt_bitlen[copy_pos]); } /* FALL THROUGH */ case ST_GET_POS_2: if (copy_pos > 1) { /* We need an additional adjustment number to * the position. */ int p = copy_pos - 1; if (!lzh_br_read_ahead(strm, &bre, p)) { if (last) goto failed;/* Truncated data.*/ state = ST_GET_POS_2; ds->copy_len = copy_len; ds->copy_pos = copy_pos; goto next_data; } copy_pos = (1 << p) + lzh_br_bits(&bre, p); lzh_br_consume(&bre, p); } /* The position is actually a distance from the last * code we had extracted and thus we have to convert * it to a position of the window. */ copy_pos = (w_pos - copy_pos - 1) & w_mask; /* FALL THROUGH */ case ST_COPY_DATA: /* * Copy `copy_len' bytes as extracted data from * the window into the output buffer. */ for (;;) { int l; l = copy_len; if (copy_pos > w_pos) { if (l > w_size - copy_pos) l = w_size - copy_pos; } else { if (l > w_size - w_pos) l = w_size - w_pos; } if ((copy_pos + l < w_pos) || (w_pos + l < copy_pos)) { /* No overlap. */ memcpy(w_buff + w_pos, w_buff + copy_pos, l); } else { const unsigned char *s; unsigned char *d; int li; d = w_buff + w_pos; s = w_buff + copy_pos; for (li = 0; li < l-1;) { d[li] = s[li];li++; d[li] = s[li];li++; } if (li < l) d[li] = s[li]; } w_pos += l; if (w_pos == w_size) { w_pos = 0; lzh_emit_window(strm, w_size); if (copy_len <= l) state = ST_GET_LITERAL; else { state = ST_COPY_DATA; ds->copy_len = copy_len - l; ds->copy_pos = (copy_pos + l) & w_mask; } goto next_data; } if (copy_len <= l) /* A copy of current pattern ended. */ break; copy_len -= l; copy_pos = (copy_pos + l) & w_mask; } state = ST_GET_LITERAL; break; } } failed: return (ds->error = ARCHIVE_FAILED); next_data: ds->br = bre; ds->blocks_avail = blocks_avail; ds->state = state; ds->w_pos = w_pos; return (ARCHIVE_OK); } static int lzh_huffman_init(struct huffman *hf, size_t len_size, int tbl_bits) { int bits; if (hf->bitlen == NULL) { hf->bitlen = malloc(len_size * sizeof(hf->bitlen[0])); if (hf->bitlen == NULL) return (ARCHIVE_FATAL); } if (hf->tbl == NULL) { if (tbl_bits < HTBL_BITS) bits = tbl_bits; else bits = HTBL_BITS; hf->tbl = malloc(((size_t)1 << bits) * sizeof(hf->tbl[0])); if (hf->tbl == NULL) return (ARCHIVE_FATAL); } if (hf->tree == NULL && tbl_bits > HTBL_BITS) { hf->tree_avail = 1 << (tbl_bits - HTBL_BITS + 4); hf->tree = malloc(hf->tree_avail * sizeof(hf->tree[0])); if (hf->tree == NULL) return (ARCHIVE_FATAL); } hf->len_size = (int)len_size; hf->tbl_bits = tbl_bits; return (ARCHIVE_OK); } static void lzh_huffman_free(struct huffman *hf) { free(hf->bitlen); free(hf->tbl); free(hf->tree); } static char bitlen_tbl[0x400] = { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 0 }; static int lzh_read_pt_bitlen(struct lzh_stream *strm, int start, int end) { struct lzh_dec *ds = strm->ds; struct lzh_br *br = &(ds->br); int c, i; for (i = start; i < end; ) { /* * bit pattern the number we need * 000 -> 0 * 001 -> 1 * 010 -> 2 * ... * 110 -> 6 * 1110 -> 7 * 11110 -> 8 * ... * 1111111111110 -> 16 */ if (!lzh_br_read_ahead(strm, br, 3)) return (i); if ((c = lzh_br_bits(br, 3)) == 7) { if (!lzh_br_read_ahead(strm, br, 13)) return (i); c = bitlen_tbl[lzh_br_bits(br, 13) & 0x3FF]; if (c) lzh_br_consume(br, c - 3); else return (-1);/* Invalid data. */ } else lzh_br_consume(br, 3); ds->pt.bitlen[i++] = c; ds->pt.freq[c]++; } return (i); } static int lzh_make_fake_table(struct huffman *hf, uint16_t c) { if (c >= hf->len_size) return (0); hf->tbl[0] = c; hf->max_bits = 0; hf->shift_bits = 0; hf->bitlen[hf->tbl[0]] = 0; return (1); } /* * Make a huffman coding table. */ static int lzh_make_huffman_table(struct huffman *hf) { uint16_t *tbl; const unsigned char *bitlen; int bitptn[17], weight[17]; int i, maxbits = 0, ptn, tbl_size, w; int diffbits, len_avail; /* * Initialize bit patterns. */ ptn = 0; for (i = 1, w = 1 << 15; i <= 16; i++, w >>= 1) { bitptn[i] = ptn; weight[i] = w; if (hf->freq[i]) { ptn += hf->freq[i] * w; maxbits = i; } } if (ptn != 0x10000 || maxbits > hf->tbl_bits) return (0);/* Invalid */ hf->max_bits = maxbits; /* * Cut out extra bits which we won't house in the table. * This preparation reduces the same calculation in the for-loop * making the table. */ if (maxbits < 16) { int ebits = 16 - maxbits; for (i = 1; i <= maxbits; i++) { bitptn[i] >>= ebits; weight[i] >>= ebits; } } if (maxbits > HTBL_BITS) { unsigned htbl_max; uint16_t *p; diffbits = maxbits - HTBL_BITS; for (i = 1; i <= HTBL_BITS; i++) { bitptn[i] >>= diffbits; weight[i] >>= diffbits; } htbl_max = bitptn[HTBL_BITS] + weight[HTBL_BITS] * hf->freq[HTBL_BITS]; p = &(hf->tbl[htbl_max]); while (p < &hf->tbl[1U<<HTBL_BITS]) *p++ = 0; } else diffbits = 0; hf->shift_bits = diffbits; /* * Make the table. */ tbl_size = 1 << HTBL_BITS; tbl = hf->tbl; bitlen = hf->bitlen; len_avail = hf->len_avail; hf->tree_used = 0; for (i = 0; i < len_avail; i++) { uint16_t *p; int len, cnt; uint16_t bit; int extlen; struct htree_t *ht; if (bitlen[i] == 0) continue; /* Get a bit pattern */ len = bitlen[i]; ptn = bitptn[len]; cnt = weight[len]; if (len <= HTBL_BITS) { /* Calculate next bit pattern */ if ((bitptn[len] = ptn + cnt) > tbl_size) return (0);/* Invalid */ /* Update the table */ p = &(tbl[ptn]); if (cnt > 7) { uint16_t *pc; cnt -= 8; pc = &p[cnt]; pc[0] = (uint16_t)i; pc[1] = (uint16_t)i; pc[2] = (uint16_t)i; pc[3] = (uint16_t)i; pc[4] = (uint16_t)i; pc[5] = (uint16_t)i; pc[6] = (uint16_t)i; pc[7] = (uint16_t)i; if (cnt > 7) { cnt -= 8; memcpy(&p[cnt], pc, 8 * sizeof(uint16_t)); pc = &p[cnt]; while (cnt > 15) { cnt -= 16; memcpy(&p[cnt], pc, 16 * sizeof(uint16_t)); } } if (cnt) memcpy(p, pc, cnt * sizeof(uint16_t)); } else { while (cnt > 1) { p[--cnt] = (uint16_t)i; p[--cnt] = (uint16_t)i; } if (cnt) p[--cnt] = (uint16_t)i; } continue; } /* * A bit length is too big to be housed to a direct table, * so we use a tree model for its extra bits. */ bitptn[len] = ptn + cnt; bit = 1U << (diffbits -1); extlen = len - HTBL_BITS; p = &(tbl[ptn >> diffbits]); if (*p == 0) { *p = len_avail + hf->tree_used; ht = &(hf->tree[hf->tree_used++]); if (hf->tree_used > hf->tree_avail) return (0);/* Invalid */ ht->left = 0; ht->right = 0; } else { if (*p < len_avail || *p >= (len_avail + hf->tree_used)) return (0);/* Invalid */ ht = &(hf->tree[*p - len_avail]); } while (--extlen > 0) { if (ptn & bit) { if (ht->left < len_avail) { ht->left = len_avail + hf->tree_used; ht = &(hf->tree[hf->tree_used++]); if (hf->tree_used > hf->tree_avail) return (0);/* Invalid */ ht->left = 0; ht->right = 0; } else { ht = &(hf->tree[ht->left - len_avail]); } } else { if (ht->right < len_avail) { ht->right = len_avail + hf->tree_used; ht = &(hf->tree[hf->tree_used++]); if (hf->tree_used > hf->tree_avail) return (0);/* Invalid */ ht->left = 0; ht->right = 0; } else { ht = &(hf->tree[ht->right - len_avail]); } } bit >>= 1; } if (ptn & bit) { if (ht->left != 0) return (0);/* Invalid */ ht->left = (uint16_t)i; } else { if (ht->right != 0) return (0);/* Invalid */ ht->right = (uint16_t)i; } } return (1); } static int lzh_decode_huffman_tree(struct huffman *hf, unsigned rbits, int c) { struct htree_t *ht; int extlen; ht = hf->tree; extlen = hf->shift_bits; while (c >= hf->len_avail) { c -= hf->len_avail; if (extlen-- <= 0 || c >= hf->tree_used) return (0); if (rbits & (1U << extlen)) c = ht[c].left; else c = ht[c].right; } return (c); } static inline int lzh_decode_huffman(struct huffman *hf, unsigned rbits) { int c; /* * At first search an index table for a bit pattern. * If it fails, search a huffman tree for. */ c = hf->tbl[rbits >> hf->shift_bits]; if (c < hf->len_avail || hf->len_avail == 0) return (c); /* This bit pattern needs to be found out at a huffman tree. */ return (lzh_decode_huffman_tree(hf, rbits, c)); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3131_0
crossvul-cpp_data_good_5271_0
/* Capstone Disassembly Engine */ /* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2015 */ #ifdef CAPSTONE_HAS_X86 #include <string.h> #include <stdlib.h> #include "X86Mapping.h" #include "X86DisassemblerDecoder.h" #include "../../utils.h" uint64_t arch_masks[9] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0, 0xffffffffffffffffLL }; static x86_reg sib_base_map[] = { X86_REG_INVALID, #define ENTRY(x) X86_REG_##x, ALL_SIB_BASES #undef ENTRY }; // Fill-ins to make the compiler happy. These constants are never actually // assigned; they are just filler to make an automatically-generated switch // statement work. enum { X86_REG_BX_SI = 500, X86_REG_BX_DI = 501, X86_REG_BP_SI = 502, X86_REG_BP_DI = 503, X86_REG_sib = 504, X86_REG_sib64 = 505 }; static x86_reg sib_index_map[] = { X86_REG_INVALID, #define ENTRY(x) X86_REG_##x, ALL_EA_BASES REGS_XMM REGS_YMM REGS_ZMM #undef ENTRY }; static x86_reg segment_map[] = { X86_REG_INVALID, X86_REG_CS, X86_REG_SS, X86_REG_DS, X86_REG_ES, X86_REG_FS, X86_REG_GS, }; x86_reg x86_map_sib_base(int r) { return sib_base_map[r]; } x86_reg x86_map_sib_index(int r) { return sib_index_map[r]; } x86_reg x86_map_segment(int r) { return segment_map[r]; } #ifndef CAPSTONE_DIET static name_map reg_name_maps[] = { { X86_REG_INVALID, NULL }, { X86_REG_AH, "ah" }, { X86_REG_AL, "al" }, { X86_REG_AX, "ax" }, { X86_REG_BH, "bh" }, { X86_REG_BL, "bl" }, { X86_REG_BP, "bp" }, { X86_REG_BPL, "bpl" }, { X86_REG_BX, "bx" }, { X86_REG_CH, "ch" }, { X86_REG_CL, "cl" }, { X86_REG_CS, "cs" }, { X86_REG_CX, "cx" }, { X86_REG_DH, "dh" }, { X86_REG_DI, "di" }, { X86_REG_DIL, "dil" }, { X86_REG_DL, "dl" }, { X86_REG_DS, "ds" }, { X86_REG_DX, "dx" }, { X86_REG_EAX, "eax" }, { X86_REG_EBP, "ebp" }, { X86_REG_EBX, "ebx" }, { X86_REG_ECX, "ecx" }, { X86_REG_EDI, "edi" }, { X86_REG_EDX, "edx" }, { X86_REG_EFLAGS, "flags" }, { X86_REG_EIP, "eip" }, { X86_REG_EIZ, "eiz" }, { X86_REG_ES, "es" }, { X86_REG_ESI, "esi" }, { X86_REG_ESP, "esp" }, { X86_REG_FPSW, "fpsw" }, { X86_REG_FS, "fs" }, { X86_REG_GS, "gs" }, { X86_REG_IP, "ip" }, { X86_REG_RAX, "rax" }, { X86_REG_RBP, "rbp" }, { X86_REG_RBX, "rbx" }, { X86_REG_RCX, "rcx" }, { X86_REG_RDI, "rdi" }, { X86_REG_RDX, "rdx" }, { X86_REG_RIP, "rip" }, { X86_REG_RIZ, "riz" }, { X86_REG_RSI, "rsi" }, { X86_REG_RSP, "rsp" }, { X86_REG_SI, "si" }, { X86_REG_SIL, "sil" }, { X86_REG_SP, "sp" }, { X86_REG_SPL, "spl" }, { X86_REG_SS, "ss" }, { X86_REG_CR0, "cr0" }, { X86_REG_CR1, "cr1" }, { X86_REG_CR2, "cr2" }, { X86_REG_CR3, "cr3" }, { X86_REG_CR4, "cr4" }, { X86_REG_CR5, "cr5" }, { X86_REG_CR6, "cr6" }, { X86_REG_CR7, "cr7" }, { X86_REG_CR8, "cr8" }, { X86_REG_CR9, "cr9" }, { X86_REG_CR10, "cr10" }, { X86_REG_CR11, "cr11" }, { X86_REG_CR12, "cr12" }, { X86_REG_CR13, "cr13" }, { X86_REG_CR14, "cr14" }, { X86_REG_CR15, "cr15" }, { X86_REG_DR0, "dr0" }, { X86_REG_DR1, "dr1" }, { X86_REG_DR2, "dr2" }, { X86_REG_DR3, "dr3" }, { X86_REG_DR4, "dr4" }, { X86_REG_DR5, "dr5" }, { X86_REG_DR6, "dr6" }, { X86_REG_DR7, "dr7" }, { X86_REG_DR8, "dr8" }, { X86_REG_DR9, "dr9" }, { X86_REG_DR10, "dr10" }, { X86_REG_DR11, "dr11" }, { X86_REG_DR12, "dr12" }, { X86_REG_DR13, "dr13" }, { X86_REG_DR14, "dr14" }, { X86_REG_DR15, "dr15" }, { X86_REG_FP0, "fp0" }, { X86_REG_FP1, "fp1" }, { X86_REG_FP2, "fp2" }, { X86_REG_FP3, "fp3" }, { X86_REG_FP4, "fp4" }, { X86_REG_FP5, "fp5" }, { X86_REG_FP6, "fp6" }, { X86_REG_FP7, "fp7" }, { X86_REG_K0, "k0" }, { X86_REG_K1, "k1" }, { X86_REG_K2, "k2" }, { X86_REG_K3, "k3" }, { X86_REG_K4, "k4" }, { X86_REG_K5, "k5" }, { X86_REG_K6, "k6" }, { X86_REG_K7, "k7" }, { X86_REG_MM0, "mm0" }, { X86_REG_MM1, "mm1" }, { X86_REG_MM2, "mm2" }, { X86_REG_MM3, "mm3" }, { X86_REG_MM4, "mm4" }, { X86_REG_MM5, "mm5" }, { X86_REG_MM6, "mm6" }, { X86_REG_MM7, "mm7" }, { X86_REG_R8, "r8" }, { X86_REG_R9, "r9" }, { X86_REG_R10, "r10" }, { X86_REG_R11, "r11" }, { X86_REG_R12, "r12" }, { X86_REG_R13, "r13" }, { X86_REG_R14, "r14" }, { X86_REG_R15, "r15" }, { X86_REG_ST0, "st0" }, { X86_REG_ST1, "st1" }, { X86_REG_ST2, "st2" }, { X86_REG_ST3, "st3" }, { X86_REG_ST4, "st4" }, { X86_REG_ST5, "st5" }, { X86_REG_ST6, "st6" }, { X86_REG_ST7, "st7" }, { X86_REG_XMM0, "xmm0" }, { X86_REG_XMM1, "xmm1" }, { X86_REG_XMM2, "xmm2" }, { X86_REG_XMM3, "xmm3" }, { X86_REG_XMM4, "xmm4" }, { X86_REG_XMM5, "xmm5" }, { X86_REG_XMM6, "xmm6" }, { X86_REG_XMM7, "xmm7" }, { X86_REG_XMM8, "xmm8" }, { X86_REG_XMM9, "xmm9" }, { X86_REG_XMM10, "xmm10" }, { X86_REG_XMM11, "xmm11" }, { X86_REG_XMM12, "xmm12" }, { X86_REG_XMM13, "xmm13" }, { X86_REG_XMM14, "xmm14" }, { X86_REG_XMM15, "xmm15" }, { X86_REG_XMM16, "xmm16" }, { X86_REG_XMM17, "xmm17" }, { X86_REG_XMM18, "xmm18" }, { X86_REG_XMM19, "xmm19" }, { X86_REG_XMM20, "xmm20" }, { X86_REG_XMM21, "xmm21" }, { X86_REG_XMM22, "xmm22" }, { X86_REG_XMM23, "xmm23" }, { X86_REG_XMM24, "xmm24" }, { X86_REG_XMM25, "xmm25" }, { X86_REG_XMM26, "xmm26" }, { X86_REG_XMM27, "xmm27" }, { X86_REG_XMM28, "xmm28" }, { X86_REG_XMM29, "xmm29" }, { X86_REG_XMM30, "xmm30" }, { X86_REG_XMM31, "xmm31" }, { X86_REG_YMM0, "ymm0" }, { X86_REG_YMM1, "ymm1" }, { X86_REG_YMM2, "ymm2" }, { X86_REG_YMM3, "ymm3" }, { X86_REG_YMM4, "ymm4" }, { X86_REG_YMM5, "ymm5" }, { X86_REG_YMM6, "ymm6" }, { X86_REG_YMM7, "ymm7" }, { X86_REG_YMM8, "ymm8" }, { X86_REG_YMM9, "ymm9" }, { X86_REG_YMM10, "ymm10" }, { X86_REG_YMM11, "ymm11" }, { X86_REG_YMM12, "ymm12" }, { X86_REG_YMM13, "ymm13" }, { X86_REG_YMM14, "ymm14" }, { X86_REG_YMM15, "ymm15" }, { X86_REG_YMM16, "ymm16" }, { X86_REG_YMM17, "ymm17" }, { X86_REG_YMM18, "ymm18" }, { X86_REG_YMM19, "ymm19" }, { X86_REG_YMM20, "ymm20" }, { X86_REG_YMM21, "ymm21" }, { X86_REG_YMM22, "ymm22" }, { X86_REG_YMM23, "ymm23" }, { X86_REG_YMM24, "ymm24" }, { X86_REG_YMM25, "ymm25" }, { X86_REG_YMM26, "ymm26" }, { X86_REG_YMM27, "ymm27" }, { X86_REG_YMM28, "ymm28" }, { X86_REG_YMM29, "ymm29" }, { X86_REG_YMM30, "ymm30" }, { X86_REG_YMM31, "ymm31" }, { X86_REG_ZMM0, "zmm0" }, { X86_REG_ZMM1, "zmm1" }, { X86_REG_ZMM2, "zmm2" }, { X86_REG_ZMM3, "zmm3" }, { X86_REG_ZMM4, "zmm4" }, { X86_REG_ZMM5, "zmm5" }, { X86_REG_ZMM6, "zmm6" }, { X86_REG_ZMM7, "zmm7" }, { X86_REG_ZMM8, "zmm8" }, { X86_REG_ZMM9, "zmm9" }, { X86_REG_ZMM10, "zmm10" }, { X86_REG_ZMM11, "zmm11" }, { X86_REG_ZMM12, "zmm12" }, { X86_REG_ZMM13, "zmm13" }, { X86_REG_ZMM14, "zmm14" }, { X86_REG_ZMM15, "zmm15" }, { X86_REG_ZMM16, "zmm16" }, { X86_REG_ZMM17, "zmm17" }, { X86_REG_ZMM18, "zmm18" }, { X86_REG_ZMM19, "zmm19" }, { X86_REG_ZMM20, "zmm20" }, { X86_REG_ZMM21, "zmm21" }, { X86_REG_ZMM22, "zmm22" }, { X86_REG_ZMM23, "zmm23" }, { X86_REG_ZMM24, "zmm24" }, { X86_REG_ZMM25, "zmm25" }, { X86_REG_ZMM26, "zmm26" }, { X86_REG_ZMM27, "zmm27" }, { X86_REG_ZMM28, "zmm28" }, { X86_REG_ZMM29, "zmm29" }, { X86_REG_ZMM30, "zmm30" }, { X86_REG_ZMM31, "zmm31" }, { X86_REG_R8B, "r8b" }, { X86_REG_R9B, "r9b" }, { X86_REG_R10B, "r10b" }, { X86_REG_R11B, "r11b" }, { X86_REG_R12B, "r12b" }, { X86_REG_R13B, "r13b" }, { X86_REG_R14B, "r14b" }, { X86_REG_R15B, "r15b" }, { X86_REG_R8D, "r8d" }, { X86_REG_R9D, "r9d" }, { X86_REG_R10D, "r10d" }, { X86_REG_R11D, "r11d" }, { X86_REG_R12D, "r12d" }, { X86_REG_R13D, "r13d" }, { X86_REG_R14D, "r14d" }, { X86_REG_R15D, "r15d" }, { X86_REG_R8W, "r8w" }, { X86_REG_R9W, "r9w" }, { X86_REG_R10W, "r10w" }, { X86_REG_R11W, "r11w" }, { X86_REG_R12W, "r12w" }, { X86_REG_R13W, "r13w" }, { X86_REG_R14W, "r14w" }, { X86_REG_R15W, "r15w" }, }; #endif // register size in non-64bit mode uint8_t regsize_map_32 [] = { 0, // { X86_REG_INVALID, NULL }, 1, // { X86_REG_AH, "ah" }, 1, // { X86_REG_AL, "al" }, 2, // { X86_REG_AX, "ax" }, 1, // { X86_REG_BH, "bh" }, 1, // { X86_REG_BL, "bl" }, 2, // { X86_REG_BP, "bp" }, 1, // { X86_REG_BPL, "bpl" }, 2, // { X86_REG_BX, "bx" }, 1, // { X86_REG_CH, "ch" }, 1, // { X86_REG_CL, "cl" }, 2, // { X86_REG_CS, "cs" }, 2, // { X86_REG_CX, "cx" }, 1, // { X86_REG_DH, "dh" }, 2, // { X86_REG_DI, "di" }, 1, // { X86_REG_DIL, "dil" }, 1, // { X86_REG_DL, "dl" }, 2, // { X86_REG_DS, "ds" }, 2, // { X86_REG_DX, "dx" }, 4, // { X86_REG_EAX, "eax" }, 4, // { X86_REG_EBP, "ebp" }, 4, // { X86_REG_EBX, "ebx" }, 4, // { X86_REG_ECX, "ecx" }, 4, // { X86_REG_EDI, "edi" }, 4, // { X86_REG_EDX, "edx" }, 4, // { X86_REG_EFLAGS, "flags" }, 4, // { X86_REG_EIP, "eip" }, 4, // { X86_REG_EIZ, "eiz" }, 2, // { X86_REG_ES, "es" }, 4, // { X86_REG_ESI, "esi" }, 4, // { X86_REG_ESP, "esp" }, 10, // { X86_REG_FPSW, "fpsw" }, 2, // { X86_REG_FS, "fs" }, 2, // { X86_REG_GS, "gs" }, 2, // { X86_REG_IP, "ip" }, 8, // { X86_REG_RAX, "rax" }, 8, // { X86_REG_RBP, "rbp" }, 8, // { X86_REG_RBX, "rbx" }, 8, // { X86_REG_RCX, "rcx" }, 8, // { X86_REG_RDI, "rdi" }, 8, // { X86_REG_RDX, "rdx" }, 8, // { X86_REG_RIP, "rip" }, 8, // { X86_REG_RIZ, "riz" }, 8, // { X86_REG_RSI, "rsi" }, 8, // { X86_REG_RSP, "rsp" }, 2, // { X86_REG_SI, "si" }, 1, // { X86_REG_SIL, "sil" }, 2, // { X86_REG_SP, "sp" }, 1, // { X86_REG_SPL, "spl" }, 2, // { X86_REG_SS, "ss" }, 4, // { X86_REG_CR0, "cr0" }, 4, // { X86_REG_CR1, "cr1" }, 4, // { X86_REG_CR2, "cr2" }, 4, // { X86_REG_CR3, "cr3" }, 4, // { X86_REG_CR4, "cr4" }, 8, // { X86_REG_CR5, "cr5" }, 8, // { X86_REG_CR6, "cr6" }, 8, // { X86_REG_CR7, "cr7" }, 8, // { X86_REG_CR8, "cr8" }, 8, // { X86_REG_CR9, "cr9" }, 8, // { X86_REG_CR10, "cr10" }, 8, // { X86_REG_CR11, "cr11" }, 8, // { X86_REG_CR12, "cr12" }, 8, // { X86_REG_CR13, "cr13" }, 8, // { X86_REG_CR14, "cr14" }, 8, // { X86_REG_CR15, "cr15" }, 4, // { X86_REG_DR0, "dr0" }, 4, // { X86_REG_DR1, "dr1" }, 4, // { X86_REG_DR2, "dr2" }, 4, // { X86_REG_DR3, "dr3" }, 4, // { X86_REG_DR4, "dr4" }, 4, // { X86_REG_DR5, "dr5" }, 4, // { X86_REG_DR6, "dr6" }, 4, // { X86_REG_DR7, "dr7" }, 4, // { X86_REG_DR8, "dr8" }, 4, // { X86_REG_DR9, "dr9" }, 4, // { X86_REG_DR10, "dr10" }, 4, // { X86_REG_DR11, "dr11" }, 4, // { X86_REG_DR12, "dr12" }, 4, // { X86_REG_DR13, "dr13" }, 4, // { X86_REG_DR14, "dr14" }, 4, // { X86_REG_DR15, "dr15" }, 10, // { X86_REG_FP0, "fp0" }, 10, // { X86_REG_FP1, "fp1" }, 10, // { X86_REG_FP2, "fp2" }, 10, // { X86_REG_FP3, "fp3" }, 10, // { X86_REG_FP4, "fp4" }, 10, // { X86_REG_FP5, "fp5" }, 10, // { X86_REG_FP6, "fp6" }, 10, // { X86_REG_FP7, "fp7" }, 2, // { X86_REG_K0, "k0" }, 2, // { X86_REG_K1, "k1" }, 2, // { X86_REG_K2, "k2" }, 2, // { X86_REG_K3, "k3" }, 2, // { X86_REG_K4, "k4" }, 2, // { X86_REG_K5, "k5" }, 2, // { X86_REG_K6, "k6" }, 2, // { X86_REG_K7, "k7" }, 8, // { X86_REG_MM0, "mm0" }, 8, // { X86_REG_MM1, "mm1" }, 8, // { X86_REG_MM2, "mm2" }, 8, // { X86_REG_MM3, "mm3" }, 8, // { X86_REG_MM4, "mm4" }, 8, // { X86_REG_MM5, "mm5" }, 8, // { X86_REG_MM6, "mm6" }, 8, // { X86_REG_MM7, "mm7" }, 8, // { X86_REG_R8, "r8" }, 8, // { X86_REG_R9, "r9" }, 8, // { X86_REG_R10, "r10" }, 8, // { X86_REG_R11, "r11" }, 8, // { X86_REG_R12, "r12" }, 8, // { X86_REG_R13, "r13" }, 8, // { X86_REG_R14, "r14" }, 8, // { X86_REG_R15, "r15" }, 10, // { X86_REG_ST0, "st0" }, 10, // { X86_REG_ST1, "st1" }, 10, // { X86_REG_ST2, "st2" }, 10, // { X86_REG_ST3, "st3" }, 10, // { X86_REG_ST4, "st4" }, 10, // { X86_REG_ST5, "st5" }, 10, // { X86_REG_ST6, "st6" }, 10, // { X86_REG_ST7, "st7" }, 16, // { X86_REG_XMM0, "xmm0" }, 16, // { X86_REG_XMM1, "xmm1" }, 16, // { X86_REG_XMM2, "xmm2" }, 16, // { X86_REG_XMM3, "xmm3" }, 16, // { X86_REG_XMM4, "xmm4" }, 16, // { X86_REG_XMM5, "xmm5" }, 16, // { X86_REG_XMM6, "xmm6" }, 16, // { X86_REG_XMM7, "xmm7" }, 16, // { X86_REG_XMM8, "xmm8" }, 16, // { X86_REG_XMM9, "xmm9" }, 16, // { X86_REG_XMM10, "xmm10" }, 16, // { X86_REG_XMM11, "xmm11" }, 16, // { X86_REG_XMM12, "xmm12" }, 16, // { X86_REG_XMM13, "xmm13" }, 16, // { X86_REG_XMM14, "xmm14" }, 16, // { X86_REG_XMM15, "xmm15" }, 16, // { X86_REG_XMM16, "xmm16" }, 16, // { X86_REG_XMM17, "xmm17" }, 16, // { X86_REG_XMM18, "xmm18" }, 16, // { X86_REG_XMM19, "xmm19" }, 16, // { X86_REG_XMM20, "xmm20" }, 16, // { X86_REG_XMM21, "xmm21" }, 16, // { X86_REG_XMM22, "xmm22" }, 16, // { X86_REG_XMM23, "xmm23" }, 16, // { X86_REG_XMM24, "xmm24" }, 16, // { X86_REG_XMM25, "xmm25" }, 16, // { X86_REG_XMM26, "xmm26" }, 16, // { X86_REG_XMM27, "xmm27" }, 16, // { X86_REG_XMM28, "xmm28" }, 16, // { X86_REG_XMM29, "xmm29" }, 16, // { X86_REG_XMM30, "xmm30" }, 16, // { X86_REG_XMM31, "xmm31" }, 32, // { X86_REG_YMM0, "ymm0" }, 32, // { X86_REG_YMM1, "ymm1" }, 32, // { X86_REG_YMM2, "ymm2" }, 32, // { X86_REG_YMM3, "ymm3" }, 32, // { X86_REG_YMM4, "ymm4" }, 32, // { X86_REG_YMM5, "ymm5" }, 32, // { X86_REG_YMM6, "ymm6" }, 32, // { X86_REG_YMM7, "ymm7" }, 32, // { X86_REG_YMM8, "ymm8" }, 32, // { X86_REG_YMM9, "ymm9" }, 32, // { X86_REG_YMM10, "ymm10" }, 32, // { X86_REG_YMM11, "ymm11" }, 32, // { X86_REG_YMM12, "ymm12" }, 32, // { X86_REG_YMM13, "ymm13" }, 32, // { X86_REG_YMM14, "ymm14" }, 32, // { X86_REG_YMM15, "ymm15" }, 32, // { X86_REG_YMM16, "ymm16" }, 32, // { X86_REG_YMM17, "ymm17" }, 32, // { X86_REG_YMM18, "ymm18" }, 32, // { X86_REG_YMM19, "ymm19" }, 32, // { X86_REG_YMM20, "ymm20" }, 32, // { X86_REG_YMM21, "ymm21" }, 32, // { X86_REG_YMM22, "ymm22" }, 32, // { X86_REG_YMM23, "ymm23" }, 32, // { X86_REG_YMM24, "ymm24" }, 32, // { X86_REG_YMM25, "ymm25" }, 32, // { X86_REG_YMM26, "ymm26" }, 32, // { X86_REG_YMM27, "ymm27" }, 32, // { X86_REG_YMM28, "ymm28" }, 32, // { X86_REG_YMM29, "ymm29" }, 32, // { X86_REG_YMM30, "ymm30" }, 32, // { X86_REG_YMM31, "ymm31" }, 64, // { X86_REG_ZMM0, "zmm0" }, 64, // { X86_REG_ZMM1, "zmm1" }, 64, // { X86_REG_ZMM2, "zmm2" }, 64, // { X86_REG_ZMM3, "zmm3" }, 64, // { X86_REG_ZMM4, "zmm4" }, 64, // { X86_REG_ZMM5, "zmm5" }, 64, // { X86_REG_ZMM6, "zmm6" }, 64, // { X86_REG_ZMM7, "zmm7" }, 64, // { X86_REG_ZMM8, "zmm8" }, 64, // { X86_REG_ZMM9, "zmm9" }, 64, // { X86_REG_ZMM10, "zmm10" }, 64, // { X86_REG_ZMM11, "zmm11" }, 64, // { X86_REG_ZMM12, "zmm12" }, 64, // { X86_REG_ZMM13, "zmm13" }, 64, // { X86_REG_ZMM14, "zmm14" }, 64, // { X86_REG_ZMM15, "zmm15" }, 64, // { X86_REG_ZMM16, "zmm16" }, 64, // { X86_REG_ZMM17, "zmm17" }, 64, // { X86_REG_ZMM18, "zmm18" }, 64, // { X86_REG_ZMM19, "zmm19" }, 64, // { X86_REG_ZMM20, "zmm20" }, 64, // { X86_REG_ZMM21, "zmm21" }, 64, // { X86_REG_ZMM22, "zmm22" }, 64, // { X86_REG_ZMM23, "zmm23" }, 64, // { X86_REG_ZMM24, "zmm24" }, 64, // { X86_REG_ZMM25, "zmm25" }, 64, // { X86_REG_ZMM26, "zmm26" }, 64, // { X86_REG_ZMM27, "zmm27" }, 64, // { X86_REG_ZMM28, "zmm28" }, 64, // { X86_REG_ZMM29, "zmm29" }, 64, // { X86_REG_ZMM30, "zmm30" }, 64, // { X86_REG_ZMM31, "zmm31" }, 1, // { X86_REG_R8B, "r8b" }, 1, // { X86_REG_R9B, "r9b" }, 1, // { X86_REG_R10B, "r10b" }, 1, // { X86_REG_R11B, "r11b" }, 1, // { X86_REG_R12B, "r12b" }, 1, // { X86_REG_R13B, "r13b" }, 1, // { X86_REG_R14B, "r14b" }, 1, // { X86_REG_R15B, "r15b" }, 4, // { X86_REG_R8D, "r8d" }, 4, // { X86_REG_R9D, "r9d" }, 4, // { X86_REG_R10D, "r10d" }, 4, // { X86_REG_R11D, "r11d" }, 4, // { X86_REG_R12D, "r12d" }, 4, // { X86_REG_R13D, "r13d" }, 4, // { X86_REG_R14D, "r14d" }, 4, // { X86_REG_R15D, "r15d" }, 2, // { X86_REG_R8W, "r8w" }, 2, // { X86_REG_R9W, "r9w" }, 2, // { X86_REG_R10W, "r10w" }, 2, // { X86_REG_R11W, "r11w" }, 2, // { X86_REG_R12W, "r12w" }, 2, // { X86_REG_R13W, "r13w" }, 2, // { X86_REG_R14W, "r14w" }, 2, // { X86_REG_R15W, "r15w" }, }; // register size in 64bit mode uint8_t regsize_map_64 [] = { 0, // { X86_REG_INVALID, NULL }, 1, // { X86_REG_AH, "ah" }, 1, // { X86_REG_AL, "al" }, 2, // { X86_REG_AX, "ax" }, 1, // { X86_REG_BH, "bh" }, 1, // { X86_REG_BL, "bl" }, 2, // { X86_REG_BP, "bp" }, 1, // { X86_REG_BPL, "bpl" }, 2, // { X86_REG_BX, "bx" }, 1, // { X86_REG_CH, "ch" }, 1, // { X86_REG_CL, "cl" }, 2, // { X86_REG_CS, "cs" }, 2, // { X86_REG_CX, "cx" }, 1, // { X86_REG_DH, "dh" }, 2, // { X86_REG_DI, "di" }, 1, // { X86_REG_DIL, "dil" }, 1, // { X86_REG_DL, "dl" }, 2, // { X86_REG_DS, "ds" }, 2, // { X86_REG_DX, "dx" }, 4, // { X86_REG_EAX, "eax" }, 4, // { X86_REG_EBP, "ebp" }, 4, // { X86_REG_EBX, "ebx" }, 4, // { X86_REG_ECX, "ecx" }, 4, // { X86_REG_EDI, "edi" }, 4, // { X86_REG_EDX, "edx" }, 8, // { X86_REG_EFLAGS, "flags" }, 4, // { X86_REG_EIP, "eip" }, 4, // { X86_REG_EIZ, "eiz" }, 2, // { X86_REG_ES, "es" }, 4, // { X86_REG_ESI, "esi" }, 4, // { X86_REG_ESP, "esp" }, 10, // { X86_REG_FPSW, "fpsw" }, 2, // { X86_REG_FS, "fs" }, 2, // { X86_REG_GS, "gs" }, 2, // { X86_REG_IP, "ip" }, 8, // { X86_REG_RAX, "rax" }, 8, // { X86_REG_RBP, "rbp" }, 8, // { X86_REG_RBX, "rbx" }, 8, // { X86_REG_RCX, "rcx" }, 8, // { X86_REG_RDI, "rdi" }, 8, // { X86_REG_RDX, "rdx" }, 8, // { X86_REG_RIP, "rip" }, 8, // { X86_REG_RIZ, "riz" }, 8, // { X86_REG_RSI, "rsi" }, 8, // { X86_REG_RSP, "rsp" }, 2, // { X86_REG_SI, "si" }, 1, // { X86_REG_SIL, "sil" }, 2, // { X86_REG_SP, "sp" }, 1, // { X86_REG_SPL, "spl" }, 2, // { X86_REG_SS, "ss" }, 8, // { X86_REG_CR0, "cr0" }, 8, // { X86_REG_CR1, "cr1" }, 8, // { X86_REG_CR2, "cr2" }, 8, // { X86_REG_CR3, "cr3" }, 8, // { X86_REG_CR4, "cr4" }, 8, // { X86_REG_CR5, "cr5" }, 8, // { X86_REG_CR6, "cr6" }, 8, // { X86_REG_CR7, "cr7" }, 8, // { X86_REG_CR8, "cr8" }, 8, // { X86_REG_CR9, "cr9" }, 8, // { X86_REG_CR10, "cr10" }, 8, // { X86_REG_CR11, "cr11" }, 8, // { X86_REG_CR12, "cr12" }, 8, // { X86_REG_CR13, "cr13" }, 8, // { X86_REG_CR14, "cr14" }, 8, // { X86_REG_CR15, "cr15" }, 8, // { X86_REG_DR0, "dr0" }, 8, // { X86_REG_DR1, "dr1" }, 8, // { X86_REG_DR2, "dr2" }, 8, // { X86_REG_DR3, "dr3" }, 8, // { X86_REG_DR4, "dr4" }, 8, // { X86_REG_DR5, "dr5" }, 8, // { X86_REG_DR6, "dr6" }, 8, // { X86_REG_DR7, "dr7" }, 8, // { X86_REG_DR8, "dr8" }, 8, // { X86_REG_DR9, "dr9" }, 8, // { X86_REG_DR10, "dr10" }, 8, // { X86_REG_DR11, "dr11" }, 8, // { X86_REG_DR12, "dr12" }, 8, // { X86_REG_DR13, "dr13" }, 8, // { X86_REG_DR14, "dr14" }, 8, // { X86_REG_DR15, "dr15" }, 10, // { X86_REG_FP0, "fp0" }, 10, // { X86_REG_FP1, "fp1" }, 10, // { X86_REG_FP2, "fp2" }, 10, // { X86_REG_FP3, "fp3" }, 10, // { X86_REG_FP4, "fp4" }, 10, // { X86_REG_FP5, "fp5" }, 10, // { X86_REG_FP6, "fp6" }, 10, // { X86_REG_FP7, "fp7" }, 2, // { X86_REG_K0, "k0" }, 2, // { X86_REG_K1, "k1" }, 2, // { X86_REG_K2, "k2" }, 2, // { X86_REG_K3, "k3" }, 2, // { X86_REG_K4, "k4" }, 2, // { X86_REG_K5, "k5" }, 2, // { X86_REG_K6, "k6" }, 2, // { X86_REG_K7, "k7" }, 8, // { X86_REG_MM0, "mm0" }, 8, // { X86_REG_MM1, "mm1" }, 8, // { X86_REG_MM2, "mm2" }, 8, // { X86_REG_MM3, "mm3" }, 8, // { X86_REG_MM4, "mm4" }, 8, // { X86_REG_MM5, "mm5" }, 8, // { X86_REG_MM6, "mm6" }, 8, // { X86_REG_MM7, "mm7" }, 8, // { X86_REG_R8, "r8" }, 8, // { X86_REG_R9, "r9" }, 8, // { X86_REG_R10, "r10" }, 8, // { X86_REG_R11, "r11" }, 8, // { X86_REG_R12, "r12" }, 8, // { X86_REG_R13, "r13" }, 8, // { X86_REG_R14, "r14" }, 8, // { X86_REG_R15, "r15" }, 10, // { X86_REG_ST0, "st0" }, 10, // { X86_REG_ST1, "st1" }, 10, // { X86_REG_ST2, "st2" }, 10, // { X86_REG_ST3, "st3" }, 10, // { X86_REG_ST4, "st4" }, 10, // { X86_REG_ST5, "st5" }, 10, // { X86_REG_ST6, "st6" }, 10, // { X86_REG_ST7, "st7" }, 16, // { X86_REG_XMM0, "xmm0" }, 16, // { X86_REG_XMM1, "xmm1" }, 16, // { X86_REG_XMM2, "xmm2" }, 16, // { X86_REG_XMM3, "xmm3" }, 16, // { X86_REG_XMM4, "xmm4" }, 16, // { X86_REG_XMM5, "xmm5" }, 16, // { X86_REG_XMM6, "xmm6" }, 16, // { X86_REG_XMM7, "xmm7" }, 16, // { X86_REG_XMM8, "xmm8" }, 16, // { X86_REG_XMM9, "xmm9" }, 16, // { X86_REG_XMM10, "xmm10" }, 16, // { X86_REG_XMM11, "xmm11" }, 16, // { X86_REG_XMM12, "xmm12" }, 16, // { X86_REG_XMM13, "xmm13" }, 16, // { X86_REG_XMM14, "xmm14" }, 16, // { X86_REG_XMM15, "xmm15" }, 16, // { X86_REG_XMM16, "xmm16" }, 16, // { X86_REG_XMM17, "xmm17" }, 16, // { X86_REG_XMM18, "xmm18" }, 16, // { X86_REG_XMM19, "xmm19" }, 16, // { X86_REG_XMM20, "xmm20" }, 16, // { X86_REG_XMM21, "xmm21" }, 16, // { X86_REG_XMM22, "xmm22" }, 16, // { X86_REG_XMM23, "xmm23" }, 16, // { X86_REG_XMM24, "xmm24" }, 16, // { X86_REG_XMM25, "xmm25" }, 16, // { X86_REG_XMM26, "xmm26" }, 16, // { X86_REG_XMM27, "xmm27" }, 16, // { X86_REG_XMM28, "xmm28" }, 16, // { X86_REG_XMM29, "xmm29" }, 16, // { X86_REG_XMM30, "xmm30" }, 16, // { X86_REG_XMM31, "xmm31" }, 32, // { X86_REG_YMM0, "ymm0" }, 32, // { X86_REG_YMM1, "ymm1" }, 32, // { X86_REG_YMM2, "ymm2" }, 32, // { X86_REG_YMM3, "ymm3" }, 32, // { X86_REG_YMM4, "ymm4" }, 32, // { X86_REG_YMM5, "ymm5" }, 32, // { X86_REG_YMM6, "ymm6" }, 32, // { X86_REG_YMM7, "ymm7" }, 32, // { X86_REG_YMM8, "ymm8" }, 32, // { X86_REG_YMM9, "ymm9" }, 32, // { X86_REG_YMM10, "ymm10" }, 32, // { X86_REG_YMM11, "ymm11" }, 32, // { X86_REG_YMM12, "ymm12" }, 32, // { X86_REG_YMM13, "ymm13" }, 32, // { X86_REG_YMM14, "ymm14" }, 32, // { X86_REG_YMM15, "ymm15" }, 32, // { X86_REG_YMM16, "ymm16" }, 32, // { X86_REG_YMM17, "ymm17" }, 32, // { X86_REG_YMM18, "ymm18" }, 32, // { X86_REG_YMM19, "ymm19" }, 32, // { X86_REG_YMM20, "ymm20" }, 32, // { X86_REG_YMM21, "ymm21" }, 32, // { X86_REG_YMM22, "ymm22" }, 32, // { X86_REG_YMM23, "ymm23" }, 32, // { X86_REG_YMM24, "ymm24" }, 32, // { X86_REG_YMM25, "ymm25" }, 32, // { X86_REG_YMM26, "ymm26" }, 32, // { X86_REG_YMM27, "ymm27" }, 32, // { X86_REG_YMM28, "ymm28" }, 32, // { X86_REG_YMM29, "ymm29" }, 32, // { X86_REG_YMM30, "ymm30" }, 32, // { X86_REG_YMM31, "ymm31" }, 64, // { X86_REG_ZMM0, "zmm0" }, 64, // { X86_REG_ZMM1, "zmm1" }, 64, // { X86_REG_ZMM2, "zmm2" }, 64, // { X86_REG_ZMM3, "zmm3" }, 64, // { X86_REG_ZMM4, "zmm4" }, 64, // { X86_REG_ZMM5, "zmm5" }, 64, // { X86_REG_ZMM6, "zmm6" }, 64, // { X86_REG_ZMM7, "zmm7" }, 64, // { X86_REG_ZMM8, "zmm8" }, 64, // { X86_REG_ZMM9, "zmm9" }, 64, // { X86_REG_ZMM10, "zmm10" }, 64, // { X86_REG_ZMM11, "zmm11" }, 64, // { X86_REG_ZMM12, "zmm12" }, 64, // { X86_REG_ZMM13, "zmm13" }, 64, // { X86_REG_ZMM14, "zmm14" }, 64, // { X86_REG_ZMM15, "zmm15" }, 64, // { X86_REG_ZMM16, "zmm16" }, 64, // { X86_REG_ZMM17, "zmm17" }, 64, // { X86_REG_ZMM18, "zmm18" }, 64, // { X86_REG_ZMM19, "zmm19" }, 64, // { X86_REG_ZMM20, "zmm20" }, 64, // { X86_REG_ZMM21, "zmm21" }, 64, // { X86_REG_ZMM22, "zmm22" }, 64, // { X86_REG_ZMM23, "zmm23" }, 64, // { X86_REG_ZMM24, "zmm24" }, 64, // { X86_REG_ZMM25, "zmm25" }, 64, // { X86_REG_ZMM26, "zmm26" }, 64, // { X86_REG_ZMM27, "zmm27" }, 64, // { X86_REG_ZMM28, "zmm28" }, 64, // { X86_REG_ZMM29, "zmm29" }, 64, // { X86_REG_ZMM30, "zmm30" }, 64, // { X86_REG_ZMM31, "zmm31" }, 1, // { X86_REG_R8B, "r8b" }, 1, // { X86_REG_R9B, "r9b" }, 1, // { X86_REG_R10B, "r10b" }, 1, // { X86_REG_R11B, "r11b" }, 1, // { X86_REG_R12B, "r12b" }, 1, // { X86_REG_R13B, "r13b" }, 1, // { X86_REG_R14B, "r14b" }, 1, // { X86_REG_R15B, "r15b" }, 4, // { X86_REG_R8D, "r8d" }, 4, // { X86_REG_R9D, "r9d" }, 4, // { X86_REG_R10D, "r10d" }, 4, // { X86_REG_R11D, "r11d" }, 4, // { X86_REG_R12D, "r12d" }, 4, // { X86_REG_R13D, "r13d" }, 4, // { X86_REG_R14D, "r14d" }, 4, // { X86_REG_R15D, "r15d" }, 2, // { X86_REG_R8W, "r8w" }, 2, // { X86_REG_R9W, "r9w" }, 2, // { X86_REG_R10W, "r10w" }, 2, // { X86_REG_R11W, "r11w" }, 2, // { X86_REG_R12W, "r12w" }, 2, // { X86_REG_R13W, "r13w" }, 2, // { X86_REG_R14W, "r14w" }, 2, // { X86_REG_R15W, "r15w" }, }; const char *X86_reg_name(csh handle, unsigned int reg) { #ifndef CAPSTONE_DIET cs_struct *ud = (cs_struct *)handle; if (reg >= X86_REG_ENDING) return NULL; if (reg == X86_REG_EFLAGS) { if (ud->mode & CS_MODE_32) return "eflags"; if (ud->mode & CS_MODE_64) return "rflags"; } return reg_name_maps[reg].name; #else return NULL; #endif } #ifndef CAPSTONE_DIET static name_map insn_name_maps[] = { { X86_INS_INVALID, NULL }, { X86_INS_AAA, "aaa" }, { X86_INS_AAD, "aad" }, { X86_INS_AAM, "aam" }, { X86_INS_AAS, "aas" }, { X86_INS_FABS, "fabs" }, { X86_INS_ADC, "adc" }, { X86_INS_ADCX, "adcx" }, { X86_INS_ADD, "add" }, { X86_INS_ADDPD, "addpd" }, { X86_INS_ADDPS, "addps" }, { X86_INS_ADDSD, "addsd" }, { X86_INS_ADDSS, "addss" }, { X86_INS_ADDSUBPD, "addsubpd" }, { X86_INS_ADDSUBPS, "addsubps" }, { X86_INS_FADD, "fadd" }, { X86_INS_FIADD, "fiadd" }, { X86_INS_FADDP, "faddp" }, { X86_INS_ADOX, "adox" }, { X86_INS_AESDECLAST, "aesdeclast" }, { X86_INS_AESDEC, "aesdec" }, { X86_INS_AESENCLAST, "aesenclast" }, { X86_INS_AESENC, "aesenc" }, { X86_INS_AESIMC, "aesimc" }, { X86_INS_AESKEYGENASSIST, "aeskeygenassist" }, { X86_INS_AND, "and" }, { X86_INS_ANDN, "andn" }, { X86_INS_ANDNPD, "andnpd" }, { X86_INS_ANDNPS, "andnps" }, { X86_INS_ANDPD, "andpd" }, { X86_INS_ANDPS, "andps" }, { X86_INS_ARPL, "arpl" }, { X86_INS_BEXTR, "bextr" }, { X86_INS_BLCFILL, "blcfill" }, { X86_INS_BLCI, "blci" }, { X86_INS_BLCIC, "blcic" }, { X86_INS_BLCMSK, "blcmsk" }, { X86_INS_BLCS, "blcs" }, { X86_INS_BLENDPD, "blendpd" }, { X86_INS_BLENDPS, "blendps" }, { X86_INS_BLENDVPD, "blendvpd" }, { X86_INS_BLENDVPS, "blendvps" }, { X86_INS_BLSFILL, "blsfill" }, { X86_INS_BLSI, "blsi" }, { X86_INS_BLSIC, "blsic" }, { X86_INS_BLSMSK, "blsmsk" }, { X86_INS_BLSR, "blsr" }, { X86_INS_BOUND, "bound" }, { X86_INS_BSF, "bsf" }, { X86_INS_BSR, "bsr" }, { X86_INS_BSWAP, "bswap" }, { X86_INS_BT, "bt" }, { X86_INS_BTC, "btc" }, { X86_INS_BTR, "btr" }, { X86_INS_BTS, "bts" }, { X86_INS_BZHI, "bzhi" }, { X86_INS_CALL, "call" }, { X86_INS_CBW, "cbw" }, { X86_INS_CDQ, "cdq" }, { X86_INS_CDQE, "cdqe" }, { X86_INS_FCHS, "fchs" }, { X86_INS_CLAC, "clac" }, { X86_INS_CLC, "clc" }, { X86_INS_CLD, "cld" }, { X86_INS_CLFLUSH, "clflush" }, { X86_INS_CLFLUSHOPT, "clflushopt" }, { X86_INS_CLGI, "clgi" }, { X86_INS_CLI, "cli" }, { X86_INS_CLTS, "clts" }, { X86_INS_CLWB, "clwb" }, { X86_INS_CMC, "cmc" }, { X86_INS_CMOVA, "cmova" }, { X86_INS_CMOVAE, "cmovae" }, { X86_INS_CMOVB, "cmovb" }, { X86_INS_CMOVBE, "cmovbe" }, { X86_INS_FCMOVBE, "fcmovbe" }, { X86_INS_FCMOVB, "fcmovb" }, { X86_INS_CMOVE, "cmove" }, { X86_INS_FCMOVE, "fcmove" }, { X86_INS_CMOVG, "cmovg" }, { X86_INS_CMOVGE, "cmovge" }, { X86_INS_CMOVL, "cmovl" }, { X86_INS_CMOVLE, "cmovle" }, { X86_INS_FCMOVNBE, "fcmovnbe" }, { X86_INS_FCMOVNB, "fcmovnb" }, { X86_INS_CMOVNE, "cmovne" }, { X86_INS_FCMOVNE, "fcmovne" }, { X86_INS_CMOVNO, "cmovno" }, { X86_INS_CMOVNP, "cmovnp" }, { X86_INS_FCMOVNU, "fcmovnu" }, { X86_INS_CMOVNS, "cmovns" }, { X86_INS_CMOVO, "cmovo" }, { X86_INS_CMOVP, "cmovp" }, { X86_INS_FCMOVU, "fcmovu" }, { X86_INS_CMOVS, "cmovs" }, { X86_INS_CMP, "cmp" }, { X86_INS_CMPSB, "cmpsb" }, { X86_INS_CMPSQ, "cmpsq" }, { X86_INS_CMPSW, "cmpsw" }, { X86_INS_CMPXCHG16B, "cmpxchg16b" }, { X86_INS_CMPXCHG, "cmpxchg" }, { X86_INS_CMPXCHG8B, "cmpxchg8b" }, { X86_INS_COMISD, "comisd" }, { X86_INS_COMISS, "comiss" }, { X86_INS_FCOMP, "fcomp" }, { X86_INS_FCOMPI, "fcompi" }, { X86_INS_FCOMI, "fcomi" }, { X86_INS_FCOM, "fcom" }, { X86_INS_FCOS, "fcos" }, { X86_INS_CPUID, "cpuid" }, { X86_INS_CQO, "cqo" }, { X86_INS_CRC32, "crc32" }, { X86_INS_CVTDQ2PD, "cvtdq2pd" }, { X86_INS_CVTDQ2PS, "cvtdq2ps" }, { X86_INS_CVTPD2DQ, "cvtpd2dq" }, { X86_INS_CVTPD2PS, "cvtpd2ps" }, { X86_INS_CVTPS2DQ, "cvtps2dq" }, { X86_INS_CVTPS2PD, "cvtps2pd" }, { X86_INS_CVTSD2SI, "cvtsd2si" }, { X86_INS_CVTSD2SS, "cvtsd2ss" }, { X86_INS_CVTSI2SD, "cvtsi2sd" }, { X86_INS_CVTSI2SS, "cvtsi2ss" }, { X86_INS_CVTSS2SD, "cvtss2sd" }, { X86_INS_CVTSS2SI, "cvtss2si" }, { X86_INS_CVTTPD2DQ, "cvttpd2dq" }, { X86_INS_CVTTPS2DQ, "cvttps2dq" }, { X86_INS_CVTTSD2SI, "cvttsd2si" }, { X86_INS_CVTTSS2SI, "cvttss2si" }, { X86_INS_CWD, "cwd" }, { X86_INS_CWDE, "cwde" }, { X86_INS_DAA, "daa" }, { X86_INS_DAS, "das" }, { X86_INS_DATA16, "data16" }, { X86_INS_DEC, "dec" }, { X86_INS_DIV, "div" }, { X86_INS_DIVPD, "divpd" }, { X86_INS_DIVPS, "divps" }, { X86_INS_FDIVR, "fdivr" }, { X86_INS_FIDIVR, "fidivr" }, { X86_INS_FDIVRP, "fdivrp" }, { X86_INS_DIVSD, "divsd" }, { X86_INS_DIVSS, "divss" }, { X86_INS_FDIV, "fdiv" }, { X86_INS_FIDIV, "fidiv" }, { X86_INS_FDIVP, "fdivp" }, { X86_INS_DPPD, "dppd" }, { X86_INS_DPPS, "dpps" }, { X86_INS_RET, "ret" }, { X86_INS_ENCLS, "encls" }, { X86_INS_ENCLU, "enclu" }, { X86_INS_ENTER, "enter" }, { X86_INS_EXTRACTPS, "extractps" }, { X86_INS_EXTRQ, "extrq" }, { X86_INS_F2XM1, "f2xm1" }, { X86_INS_LCALL, "lcall" }, { X86_INS_LJMP, "ljmp" }, { X86_INS_FBLD, "fbld" }, { X86_INS_FBSTP, "fbstp" }, { X86_INS_FCOMPP, "fcompp" }, { X86_INS_FDECSTP, "fdecstp" }, { X86_INS_FEMMS, "femms" }, { X86_INS_FFREE, "ffree" }, { X86_INS_FICOM, "ficom" }, { X86_INS_FICOMP, "ficomp" }, { X86_INS_FINCSTP, "fincstp" }, { X86_INS_FLDCW, "fldcw" }, { X86_INS_FLDENV, "fldenv" }, { X86_INS_FLDL2E, "fldl2e" }, { X86_INS_FLDL2T, "fldl2t" }, { X86_INS_FLDLG2, "fldlg2" }, { X86_INS_FLDLN2, "fldln2" }, { X86_INS_FLDPI, "fldpi" }, { X86_INS_FNCLEX, "fnclex" }, { X86_INS_FNINIT, "fninit" }, { X86_INS_FNOP, "fnop" }, { X86_INS_FNSTCW, "fnstcw" }, { X86_INS_FNSTSW, "fnstsw" }, { X86_INS_FPATAN, "fpatan" }, { X86_INS_FPREM, "fprem" }, { X86_INS_FPREM1, "fprem1" }, { X86_INS_FPTAN, "fptan" }, { X86_INS_FFREEP, "ffreep" }, { X86_INS_FRNDINT, "frndint" }, { X86_INS_FRSTOR, "frstor" }, { X86_INS_FNSAVE, "fnsave" }, { X86_INS_FSCALE, "fscale" }, { X86_INS_FSETPM, "fsetpm" }, { X86_INS_FSINCOS, "fsincos" }, { X86_INS_FNSTENV, "fnstenv" }, { X86_INS_FXAM, "fxam" }, { X86_INS_FXRSTOR, "fxrstor" }, { X86_INS_FXRSTOR64, "fxrstor64" }, { X86_INS_FXSAVE, "fxsave" }, { X86_INS_FXSAVE64, "fxsave64" }, { X86_INS_FXTRACT, "fxtract" }, { X86_INS_FYL2X, "fyl2x" }, { X86_INS_FYL2XP1, "fyl2xp1" }, { X86_INS_MOVAPD, "movapd" }, { X86_INS_MOVAPS, "movaps" }, { X86_INS_ORPD, "orpd" }, { X86_INS_ORPS, "orps" }, { X86_INS_VMOVAPD, "vmovapd" }, { X86_INS_VMOVAPS, "vmovaps" }, { X86_INS_XORPD, "xorpd" }, { X86_INS_XORPS, "xorps" }, { X86_INS_GETSEC, "getsec" }, { X86_INS_HADDPD, "haddpd" }, { X86_INS_HADDPS, "haddps" }, { X86_INS_HLT, "hlt" }, { X86_INS_HSUBPD, "hsubpd" }, { X86_INS_HSUBPS, "hsubps" }, { X86_INS_IDIV, "idiv" }, { X86_INS_FILD, "fild" }, { X86_INS_IMUL, "imul" }, { X86_INS_IN, "in" }, { X86_INS_INC, "inc" }, { X86_INS_INSB, "insb" }, { X86_INS_INSERTPS, "insertps" }, { X86_INS_INSERTQ, "insertq" }, { X86_INS_INSD, "insd" }, { X86_INS_INSW, "insw" }, { X86_INS_INT, "int" }, { X86_INS_INT1, "int1" }, { X86_INS_INT3, "int3" }, { X86_INS_INTO, "into" }, { X86_INS_INVD, "invd" }, { X86_INS_INVEPT, "invept" }, { X86_INS_INVLPG, "invlpg" }, { X86_INS_INVLPGA, "invlpga" }, { X86_INS_INVPCID, "invpcid" }, { X86_INS_INVVPID, "invvpid" }, { X86_INS_IRET, "iret" }, { X86_INS_IRETD, "iretd" }, { X86_INS_IRETQ, "iretq" }, { X86_INS_FISTTP, "fisttp" }, { X86_INS_FIST, "fist" }, { X86_INS_FISTP, "fistp" }, { X86_INS_UCOMISD, "ucomisd" }, { X86_INS_UCOMISS, "ucomiss" }, { X86_INS_VCOMISD, "vcomisd" }, { X86_INS_VCOMISS, "vcomiss" }, { X86_INS_VCVTSD2SS, "vcvtsd2ss" }, { X86_INS_VCVTSI2SD, "vcvtsi2sd" }, { X86_INS_VCVTSI2SS, "vcvtsi2ss" }, { X86_INS_VCVTSS2SD, "vcvtss2sd" }, { X86_INS_VCVTTSD2SI, "vcvttsd2si" }, { X86_INS_VCVTTSD2USI, "vcvttsd2usi" }, { X86_INS_VCVTTSS2SI, "vcvttss2si" }, { X86_INS_VCVTTSS2USI, "vcvttss2usi" }, { X86_INS_VCVTUSI2SD, "vcvtusi2sd" }, { X86_INS_VCVTUSI2SS, "vcvtusi2ss" }, { X86_INS_VUCOMISD, "vucomisd" }, { X86_INS_VUCOMISS, "vucomiss" }, { X86_INS_JAE, "jae" }, { X86_INS_JA, "ja" }, { X86_INS_JBE, "jbe" }, { X86_INS_JB, "jb" }, { X86_INS_JCXZ, "jcxz" }, { X86_INS_JECXZ, "jecxz" }, { X86_INS_JE, "je" }, { X86_INS_JGE, "jge" }, { X86_INS_JG, "jg" }, { X86_INS_JLE, "jle" }, { X86_INS_JL, "jl" }, { X86_INS_JMP, "jmp" }, { X86_INS_JNE, "jne" }, { X86_INS_JNO, "jno" }, { X86_INS_JNP, "jnp" }, { X86_INS_JNS, "jns" }, { X86_INS_JO, "jo" }, { X86_INS_JP, "jp" }, { X86_INS_JRCXZ, "jrcxz" }, { X86_INS_JS, "js" }, { X86_INS_KANDB, "kandb" }, { X86_INS_KANDD, "kandd" }, { X86_INS_KANDNB, "kandnb" }, { X86_INS_KANDND, "kandnd" }, { X86_INS_KANDNQ, "kandnq" }, { X86_INS_KANDNW, "kandnw" }, { X86_INS_KANDQ, "kandq" }, { X86_INS_KANDW, "kandw" }, { X86_INS_KMOVB, "kmovb" }, { X86_INS_KMOVD, "kmovd" }, { X86_INS_KMOVQ, "kmovq" }, { X86_INS_KMOVW, "kmovw" }, { X86_INS_KNOTB, "knotb" }, { X86_INS_KNOTD, "knotd" }, { X86_INS_KNOTQ, "knotq" }, { X86_INS_KNOTW, "knotw" }, { X86_INS_KORB, "korb" }, { X86_INS_KORD, "kord" }, { X86_INS_KORQ, "korq" }, { X86_INS_KORTESTB, "kortestb" }, { X86_INS_KORTESTD, "kortestd" }, { X86_INS_KORTESTQ, "kortestq" }, { X86_INS_KORTESTW, "kortestw" }, { X86_INS_KORW, "korw" }, { X86_INS_KSHIFTLB, "kshiftlb" }, { X86_INS_KSHIFTLD, "kshiftld" }, { X86_INS_KSHIFTLQ, "kshiftlq" }, { X86_INS_KSHIFTLW, "kshiftlw" }, { X86_INS_KSHIFTRB, "kshiftrb" }, { X86_INS_KSHIFTRD, "kshiftrd" }, { X86_INS_KSHIFTRQ, "kshiftrq" }, { X86_INS_KSHIFTRW, "kshiftrw" }, { X86_INS_KUNPCKBW, "kunpckbw" }, { X86_INS_KXNORB, "kxnorb" }, { X86_INS_KXNORD, "kxnord" }, { X86_INS_KXNORQ, "kxnorq" }, { X86_INS_KXNORW, "kxnorw" }, { X86_INS_KXORB, "kxorb" }, { X86_INS_KXORD, "kxord" }, { X86_INS_KXORQ, "kxorq" }, { X86_INS_KXORW, "kxorw" }, { X86_INS_LAHF, "lahf" }, { X86_INS_LAR, "lar" }, { X86_INS_LDDQU, "lddqu" }, { X86_INS_LDMXCSR, "ldmxcsr" }, { X86_INS_LDS, "lds" }, { X86_INS_FLDZ, "fldz" }, { X86_INS_FLD1, "fld1" }, { X86_INS_FLD, "fld" }, { X86_INS_LEA, "lea" }, { X86_INS_LEAVE, "leave" }, { X86_INS_LES, "les" }, { X86_INS_LFENCE, "lfence" }, { X86_INS_LFS, "lfs" }, { X86_INS_LGDT, "lgdt" }, { X86_INS_LGS, "lgs" }, { X86_INS_LIDT, "lidt" }, { X86_INS_LLDT, "lldt" }, { X86_INS_LMSW, "lmsw" }, { X86_INS_OR, "or" }, { X86_INS_SUB, "sub" }, { X86_INS_XOR, "xor" }, { X86_INS_LODSB, "lodsb" }, { X86_INS_LODSD, "lodsd" }, { X86_INS_LODSQ, "lodsq" }, { X86_INS_LODSW, "lodsw" }, { X86_INS_LOOP, "loop" }, { X86_INS_LOOPE, "loope" }, { X86_INS_LOOPNE, "loopne" }, { X86_INS_RETF, "retf" }, { X86_INS_RETFQ, "retfq" }, { X86_INS_LSL, "lsl" }, { X86_INS_LSS, "lss" }, { X86_INS_LTR, "ltr" }, { X86_INS_XADD, "xadd" }, { X86_INS_LZCNT, "lzcnt" }, { X86_INS_MASKMOVDQU, "maskmovdqu" }, { X86_INS_MAXPD, "maxpd" }, { X86_INS_MAXPS, "maxps" }, { X86_INS_MAXSD, "maxsd" }, { X86_INS_MAXSS, "maxss" }, { X86_INS_MFENCE, "mfence" }, { X86_INS_MINPD, "minpd" }, { X86_INS_MINPS, "minps" }, { X86_INS_MINSD, "minsd" }, { X86_INS_MINSS, "minss" }, { X86_INS_CVTPD2PI, "cvtpd2pi" }, { X86_INS_CVTPI2PD, "cvtpi2pd" }, { X86_INS_CVTPI2PS, "cvtpi2ps" }, { X86_INS_CVTPS2PI, "cvtps2pi" }, { X86_INS_CVTTPD2PI, "cvttpd2pi" }, { X86_INS_CVTTPS2PI, "cvttps2pi" }, { X86_INS_EMMS, "emms" }, { X86_INS_MASKMOVQ, "maskmovq" }, { X86_INS_MOVD, "movd" }, { X86_INS_MOVDQ2Q, "movdq2q" }, { X86_INS_MOVNTQ, "movntq" }, { X86_INS_MOVQ2DQ, "movq2dq" }, { X86_INS_MOVQ, "movq" }, { X86_INS_PABSB, "pabsb" }, { X86_INS_PABSD, "pabsd" }, { X86_INS_PABSW, "pabsw" }, { X86_INS_PACKSSDW, "packssdw" }, { X86_INS_PACKSSWB, "packsswb" }, { X86_INS_PACKUSWB, "packuswb" }, { X86_INS_PADDB, "paddb" }, { X86_INS_PADDD, "paddd" }, { X86_INS_PADDQ, "paddq" }, { X86_INS_PADDSB, "paddsb" }, { X86_INS_PADDSW, "paddsw" }, { X86_INS_PADDUSB, "paddusb" }, { X86_INS_PADDUSW, "paddusw" }, { X86_INS_PADDW, "paddw" }, { X86_INS_PALIGNR, "palignr" }, { X86_INS_PANDN, "pandn" }, { X86_INS_PAND, "pand" }, { X86_INS_PAVGB, "pavgb" }, { X86_INS_PAVGW, "pavgw" }, { X86_INS_PCMPEQB, "pcmpeqb" }, { X86_INS_PCMPEQD, "pcmpeqd" }, { X86_INS_PCMPEQW, "pcmpeqw" }, { X86_INS_PCMPGTB, "pcmpgtb" }, { X86_INS_PCMPGTD, "pcmpgtd" }, { X86_INS_PCMPGTW, "pcmpgtw" }, { X86_INS_PEXTRW, "pextrw" }, { X86_INS_PHADDSW, "phaddsw" }, { X86_INS_PHADDW, "phaddw" }, { X86_INS_PHADDD, "phaddd" }, { X86_INS_PHSUBD, "phsubd" }, { X86_INS_PHSUBSW, "phsubsw" }, { X86_INS_PHSUBW, "phsubw" }, { X86_INS_PINSRW, "pinsrw" }, { X86_INS_PMADDUBSW, "pmaddubsw" }, { X86_INS_PMADDWD, "pmaddwd" }, { X86_INS_PMAXSW, "pmaxsw" }, { X86_INS_PMAXUB, "pmaxub" }, { X86_INS_PMINSW, "pminsw" }, { X86_INS_PMINUB, "pminub" }, { X86_INS_PMOVMSKB, "pmovmskb" }, { X86_INS_PMULHRSW, "pmulhrsw" }, { X86_INS_PMULHUW, "pmulhuw" }, { X86_INS_PMULHW, "pmulhw" }, { X86_INS_PMULLW, "pmullw" }, { X86_INS_PMULUDQ, "pmuludq" }, { X86_INS_POR, "por" }, { X86_INS_PSADBW, "psadbw" }, { X86_INS_PSHUFB, "pshufb" }, { X86_INS_PSHUFW, "pshufw" }, { X86_INS_PSIGNB, "psignb" }, { X86_INS_PSIGND, "psignd" }, { X86_INS_PSIGNW, "psignw" }, { X86_INS_PSLLD, "pslld" }, { X86_INS_PSLLQ, "psllq" }, { X86_INS_PSLLW, "psllw" }, { X86_INS_PSRAD, "psrad" }, { X86_INS_PSRAW, "psraw" }, { X86_INS_PSRLD, "psrld" }, { X86_INS_PSRLQ, "psrlq" }, { X86_INS_PSRLW, "psrlw" }, { X86_INS_PSUBB, "psubb" }, { X86_INS_PSUBD, "psubd" }, { X86_INS_PSUBQ, "psubq" }, { X86_INS_PSUBSB, "psubsb" }, { X86_INS_PSUBSW, "psubsw" }, { X86_INS_PSUBUSB, "psubusb" }, { X86_INS_PSUBUSW, "psubusw" }, { X86_INS_PSUBW, "psubw" }, { X86_INS_PUNPCKHBW, "punpckhbw" }, { X86_INS_PUNPCKHDQ, "punpckhdq" }, { X86_INS_PUNPCKHWD, "punpckhwd" }, { X86_INS_PUNPCKLBW, "punpcklbw" }, { X86_INS_PUNPCKLDQ, "punpckldq" }, { X86_INS_PUNPCKLWD, "punpcklwd" }, { X86_INS_PXOR, "pxor" }, { X86_INS_MONITOR, "monitor" }, { X86_INS_MONTMUL, "montmul" }, { X86_INS_MOV, "mov" }, { X86_INS_MOVABS, "movabs" }, { X86_INS_MOVBE, "movbe" }, { X86_INS_MOVDDUP, "movddup" }, { X86_INS_MOVDQA, "movdqa" }, { X86_INS_MOVDQU, "movdqu" }, { X86_INS_MOVHLPS, "movhlps" }, { X86_INS_MOVHPD, "movhpd" }, { X86_INS_MOVHPS, "movhps" }, { X86_INS_MOVLHPS, "movlhps" }, { X86_INS_MOVLPD, "movlpd" }, { X86_INS_MOVLPS, "movlps" }, { X86_INS_MOVMSKPD, "movmskpd" }, { X86_INS_MOVMSKPS, "movmskps" }, { X86_INS_MOVNTDQA, "movntdqa" }, { X86_INS_MOVNTDQ, "movntdq" }, { X86_INS_MOVNTI, "movnti" }, { X86_INS_MOVNTPD, "movntpd" }, { X86_INS_MOVNTPS, "movntps" }, { X86_INS_MOVNTSD, "movntsd" }, { X86_INS_MOVNTSS, "movntss" }, { X86_INS_MOVSB, "movsb" }, { X86_INS_MOVSD, "movsd" }, { X86_INS_MOVSHDUP, "movshdup" }, { X86_INS_MOVSLDUP, "movsldup" }, { X86_INS_MOVSQ, "movsq" }, { X86_INS_MOVSS, "movss" }, { X86_INS_MOVSW, "movsw" }, { X86_INS_MOVSX, "movsx" }, { X86_INS_MOVSXD, "movsxd" }, { X86_INS_MOVUPD, "movupd" }, { X86_INS_MOVUPS, "movups" }, { X86_INS_MOVZX, "movzx" }, { X86_INS_MPSADBW, "mpsadbw" }, { X86_INS_MUL, "mul" }, { X86_INS_MULPD, "mulpd" }, { X86_INS_MULPS, "mulps" }, { X86_INS_MULSD, "mulsd" }, { X86_INS_MULSS, "mulss" }, { X86_INS_MULX, "mulx" }, { X86_INS_FMUL, "fmul" }, { X86_INS_FIMUL, "fimul" }, { X86_INS_FMULP, "fmulp" }, { X86_INS_MWAIT, "mwait" }, { X86_INS_NEG, "neg" }, { X86_INS_NOP, "nop" }, { X86_INS_NOT, "not" }, { X86_INS_OUT, "out" }, { X86_INS_OUTSB, "outsb" }, { X86_INS_OUTSD, "outsd" }, { X86_INS_OUTSW, "outsw" }, { X86_INS_PACKUSDW, "packusdw" }, { X86_INS_PAUSE, "pause" }, { X86_INS_PAVGUSB, "pavgusb" }, { X86_INS_PBLENDVB, "pblendvb" }, { X86_INS_PBLENDW, "pblendw" }, { X86_INS_PCLMULQDQ, "pclmulqdq" }, { X86_INS_PCMPEQQ, "pcmpeqq" }, { X86_INS_PCMPESTRI, "pcmpestri" }, { X86_INS_PCMPESTRM, "pcmpestrm" }, { X86_INS_PCMPGTQ, "pcmpgtq" }, { X86_INS_PCMPISTRI, "pcmpistri" }, { X86_INS_PCMPISTRM, "pcmpistrm" }, { X86_INS_PCOMMIT, "pcommit" }, { X86_INS_PDEP, "pdep" }, { X86_INS_PEXT, "pext" }, { X86_INS_PEXTRB, "pextrb" }, { X86_INS_PEXTRD, "pextrd" }, { X86_INS_PEXTRQ, "pextrq" }, { X86_INS_PF2ID, "pf2id" }, { X86_INS_PF2IW, "pf2iw" }, { X86_INS_PFACC, "pfacc" }, { X86_INS_PFADD, "pfadd" }, { X86_INS_PFCMPEQ, "pfcmpeq" }, { X86_INS_PFCMPGE, "pfcmpge" }, { X86_INS_PFCMPGT, "pfcmpgt" }, { X86_INS_PFMAX, "pfmax" }, { X86_INS_PFMIN, "pfmin" }, { X86_INS_PFMUL, "pfmul" }, { X86_INS_PFNACC, "pfnacc" }, { X86_INS_PFPNACC, "pfpnacc" }, { X86_INS_PFRCPIT1, "pfrcpit1" }, { X86_INS_PFRCPIT2, "pfrcpit2" }, { X86_INS_PFRCP, "pfrcp" }, { X86_INS_PFRSQIT1, "pfrsqit1" }, { X86_INS_PFRSQRT, "pfrsqrt" }, { X86_INS_PFSUBR, "pfsubr" }, { X86_INS_PFSUB, "pfsub" }, { X86_INS_PHMINPOSUW, "phminposuw" }, { X86_INS_PI2FD, "pi2fd" }, { X86_INS_PI2FW, "pi2fw" }, { X86_INS_PINSRB, "pinsrb" }, { X86_INS_PINSRD, "pinsrd" }, { X86_INS_PINSRQ, "pinsrq" }, { X86_INS_PMAXSB, "pmaxsb" }, { X86_INS_PMAXSD, "pmaxsd" }, { X86_INS_PMAXUD, "pmaxud" }, { X86_INS_PMAXUW, "pmaxuw" }, { X86_INS_PMINSB, "pminsb" }, { X86_INS_PMINSD, "pminsd" }, { X86_INS_PMINUD, "pminud" }, { X86_INS_PMINUW, "pminuw" }, { X86_INS_PMOVSXBD, "pmovsxbd" }, { X86_INS_PMOVSXBQ, "pmovsxbq" }, { X86_INS_PMOVSXBW, "pmovsxbw" }, { X86_INS_PMOVSXDQ, "pmovsxdq" }, { X86_INS_PMOVSXWD, "pmovsxwd" }, { X86_INS_PMOVSXWQ, "pmovsxwq" }, { X86_INS_PMOVZXBD, "pmovzxbd" }, { X86_INS_PMOVZXBQ, "pmovzxbq" }, { X86_INS_PMOVZXBW, "pmovzxbw" }, { X86_INS_PMOVZXDQ, "pmovzxdq" }, { X86_INS_PMOVZXWD, "pmovzxwd" }, { X86_INS_PMOVZXWQ, "pmovzxwq" }, { X86_INS_PMULDQ, "pmuldq" }, { X86_INS_PMULHRW, "pmulhrw" }, { X86_INS_PMULLD, "pmulld" }, { X86_INS_POP, "pop" }, { X86_INS_POPAW, "popaw" }, { X86_INS_POPAL, "popal" }, { X86_INS_POPCNT, "popcnt" }, { X86_INS_POPF, "popf" }, { X86_INS_POPFD, "popfd" }, { X86_INS_POPFQ, "popfq" }, { X86_INS_PREFETCH, "prefetch" }, { X86_INS_PREFETCHNTA, "prefetchnta" }, { X86_INS_PREFETCHT0, "prefetcht0" }, { X86_INS_PREFETCHT1, "prefetcht1" }, { X86_INS_PREFETCHT2, "prefetcht2" }, { X86_INS_PREFETCHW, "prefetchw" }, { X86_INS_PSHUFD, "pshufd" }, { X86_INS_PSHUFHW, "pshufhw" }, { X86_INS_PSHUFLW, "pshuflw" }, { X86_INS_PSLLDQ, "pslldq" }, { X86_INS_PSRLDQ, "psrldq" }, { X86_INS_PSWAPD, "pswapd" }, { X86_INS_PTEST, "ptest" }, { X86_INS_PUNPCKHQDQ, "punpckhqdq" }, { X86_INS_PUNPCKLQDQ, "punpcklqdq" }, { X86_INS_PUSH, "push" }, { X86_INS_PUSHAW, "pushaw" }, { X86_INS_PUSHAL, "pushal" }, { X86_INS_PUSHF, "pushf" }, { X86_INS_PUSHFD, "pushfd" }, { X86_INS_PUSHFQ, "pushfq" }, { X86_INS_RCL, "rcl" }, { X86_INS_RCPPS, "rcpps" }, { X86_INS_RCPSS, "rcpss" }, { X86_INS_RCR, "rcr" }, { X86_INS_RDFSBASE, "rdfsbase" }, { X86_INS_RDGSBASE, "rdgsbase" }, { X86_INS_RDMSR, "rdmsr" }, { X86_INS_RDPMC, "rdpmc" }, { X86_INS_RDRAND, "rdrand" }, { X86_INS_RDSEED, "rdseed" }, { X86_INS_RDTSC, "rdtsc" }, { X86_INS_RDTSCP, "rdtscp" }, { X86_INS_ROL, "rol" }, { X86_INS_ROR, "ror" }, { X86_INS_RORX, "rorx" }, { X86_INS_ROUNDPD, "roundpd" }, { X86_INS_ROUNDPS, "roundps" }, { X86_INS_ROUNDSD, "roundsd" }, { X86_INS_ROUNDSS, "roundss" }, { X86_INS_RSM, "rsm" }, { X86_INS_RSQRTPS, "rsqrtps" }, { X86_INS_RSQRTSS, "rsqrtss" }, { X86_INS_SAHF, "sahf" }, { X86_INS_SAL, "sal" }, { X86_INS_SALC, "salc" }, { X86_INS_SAR, "sar" }, { X86_INS_SARX, "sarx" }, { X86_INS_SBB, "sbb" }, { X86_INS_SCASB, "scasb" }, { X86_INS_SCASD, "scasd" }, { X86_INS_SCASQ, "scasq" }, { X86_INS_SCASW, "scasw" }, { X86_INS_SETAE, "setae" }, { X86_INS_SETA, "seta" }, { X86_INS_SETBE, "setbe" }, { X86_INS_SETB, "setb" }, { X86_INS_SETE, "sete" }, { X86_INS_SETGE, "setge" }, { X86_INS_SETG, "setg" }, { X86_INS_SETLE, "setle" }, { X86_INS_SETL, "setl" }, { X86_INS_SETNE, "setne" }, { X86_INS_SETNO, "setno" }, { X86_INS_SETNP, "setnp" }, { X86_INS_SETNS, "setns" }, { X86_INS_SETO, "seto" }, { X86_INS_SETP, "setp" }, { X86_INS_SETS, "sets" }, { X86_INS_SFENCE, "sfence" }, { X86_INS_SGDT, "sgdt" }, { X86_INS_SHA1MSG1, "sha1msg1" }, { X86_INS_SHA1MSG2, "sha1msg2" }, { X86_INS_SHA1NEXTE, "sha1nexte" }, { X86_INS_SHA1RNDS4, "sha1rnds4" }, { X86_INS_SHA256MSG1, "sha256msg1" }, { X86_INS_SHA256MSG2, "sha256msg2" }, { X86_INS_SHA256RNDS2, "sha256rnds2" }, { X86_INS_SHL, "shl" }, { X86_INS_SHLD, "shld" }, { X86_INS_SHLX, "shlx" }, { X86_INS_SHR, "shr" }, { X86_INS_SHRD, "shrd" }, { X86_INS_SHRX, "shrx" }, { X86_INS_SHUFPD, "shufpd" }, { X86_INS_SHUFPS, "shufps" }, { X86_INS_SIDT, "sidt" }, { X86_INS_FSIN, "fsin" }, { X86_INS_SKINIT, "skinit" }, { X86_INS_SLDT, "sldt" }, { X86_INS_SMSW, "smsw" }, { X86_INS_SQRTPD, "sqrtpd" }, { X86_INS_SQRTPS, "sqrtps" }, { X86_INS_SQRTSD, "sqrtsd" }, { X86_INS_SQRTSS, "sqrtss" }, { X86_INS_FSQRT, "fsqrt" }, { X86_INS_STAC, "stac" }, { X86_INS_STC, "stc" }, { X86_INS_STD, "std" }, { X86_INS_STGI, "stgi" }, { X86_INS_STI, "sti" }, { X86_INS_STMXCSR, "stmxcsr" }, { X86_INS_STOSB, "stosb" }, { X86_INS_STOSD, "stosd" }, { X86_INS_STOSQ, "stosq" }, { X86_INS_STOSW, "stosw" }, { X86_INS_STR, "str" }, { X86_INS_FST, "fst" }, { X86_INS_FSTP, "fstp" }, { X86_INS_FSTPNCE, "fstpnce" }, { X86_INS_FXCH, "fxch" }, { X86_INS_SUBPD, "subpd" }, { X86_INS_SUBPS, "subps" }, { X86_INS_FSUBR, "fsubr" }, { X86_INS_FISUBR, "fisubr" }, { X86_INS_FSUBRP, "fsubrp" }, { X86_INS_SUBSD, "subsd" }, { X86_INS_SUBSS, "subss" }, { X86_INS_FSUB, "fsub" }, { X86_INS_FISUB, "fisub" }, { X86_INS_FSUBP, "fsubp" }, { X86_INS_SWAPGS, "swapgs" }, { X86_INS_SYSCALL, "syscall" }, { X86_INS_SYSENTER, "sysenter" }, { X86_INS_SYSEXIT, "sysexit" }, { X86_INS_SYSRET, "sysret" }, { X86_INS_T1MSKC, "t1mskc" }, { X86_INS_TEST, "test" }, { X86_INS_UD2, "ud2" }, { X86_INS_FTST, "ftst" }, { X86_INS_TZCNT, "tzcnt" }, { X86_INS_TZMSK, "tzmsk" }, { X86_INS_FUCOMPI, "fucompi" }, { X86_INS_FUCOMI, "fucomi" }, { X86_INS_FUCOMPP, "fucompp" }, { X86_INS_FUCOMP, "fucomp" }, { X86_INS_FUCOM, "fucom" }, { X86_INS_UD2B, "ud2b" }, { X86_INS_UNPCKHPD, "unpckhpd" }, { X86_INS_UNPCKHPS, "unpckhps" }, { X86_INS_UNPCKLPD, "unpcklpd" }, { X86_INS_UNPCKLPS, "unpcklps" }, { X86_INS_VADDPD, "vaddpd" }, { X86_INS_VADDPS, "vaddps" }, { X86_INS_VADDSD, "vaddsd" }, { X86_INS_VADDSS, "vaddss" }, { X86_INS_VADDSUBPD, "vaddsubpd" }, { X86_INS_VADDSUBPS, "vaddsubps" }, { X86_INS_VAESDECLAST, "vaesdeclast" }, { X86_INS_VAESDEC, "vaesdec" }, { X86_INS_VAESENCLAST, "vaesenclast" }, { X86_INS_VAESENC, "vaesenc" }, { X86_INS_VAESIMC, "vaesimc" }, { X86_INS_VAESKEYGENASSIST, "vaeskeygenassist" }, { X86_INS_VALIGND, "valignd" }, { X86_INS_VALIGNQ, "valignq" }, { X86_INS_VANDNPD, "vandnpd" }, { X86_INS_VANDNPS, "vandnps" }, { X86_INS_VANDPD, "vandpd" }, { X86_INS_VANDPS, "vandps" }, { X86_INS_VBLENDMPD, "vblendmpd" }, { X86_INS_VBLENDMPS, "vblendmps" }, { X86_INS_VBLENDPD, "vblendpd" }, { X86_INS_VBLENDPS, "vblendps" }, { X86_INS_VBLENDVPD, "vblendvpd" }, { X86_INS_VBLENDVPS, "vblendvps" }, { X86_INS_VBROADCASTF128, "vbroadcastf128" }, { X86_INS_VBROADCASTI32X4, "vbroadcasti32x4" }, { X86_INS_VBROADCASTI64X4, "vbroadcasti64x4" }, { X86_INS_VBROADCASTSD, "vbroadcastsd" }, { X86_INS_VBROADCASTSS, "vbroadcastss" }, { X86_INS_VCOMPRESSPD, "vcompresspd" }, { X86_INS_VCOMPRESSPS, "vcompressps" }, { X86_INS_VCVTDQ2PD, "vcvtdq2pd" }, { X86_INS_VCVTDQ2PS, "vcvtdq2ps" }, { X86_INS_VCVTPD2DQX, "vcvtpd2dqx" }, { X86_INS_VCVTPD2DQ, "vcvtpd2dq" }, { X86_INS_VCVTPD2PSX, "vcvtpd2psx" }, { X86_INS_VCVTPD2PS, "vcvtpd2ps" }, { X86_INS_VCVTPD2UDQ, "vcvtpd2udq" }, { X86_INS_VCVTPH2PS, "vcvtph2ps" }, { X86_INS_VCVTPS2DQ, "vcvtps2dq" }, { X86_INS_VCVTPS2PD, "vcvtps2pd" }, { X86_INS_VCVTPS2PH, "vcvtps2ph" }, { X86_INS_VCVTPS2UDQ, "vcvtps2udq" }, { X86_INS_VCVTSD2SI, "vcvtsd2si" }, { X86_INS_VCVTSD2USI, "vcvtsd2usi" }, { X86_INS_VCVTSS2SI, "vcvtss2si" }, { X86_INS_VCVTSS2USI, "vcvtss2usi" }, { X86_INS_VCVTTPD2DQX, "vcvttpd2dqx" }, { X86_INS_VCVTTPD2DQ, "vcvttpd2dq" }, { X86_INS_VCVTTPD2UDQ, "vcvttpd2udq" }, { X86_INS_VCVTTPS2DQ, "vcvttps2dq" }, { X86_INS_VCVTTPS2UDQ, "vcvttps2udq" }, { X86_INS_VCVTUDQ2PD, "vcvtudq2pd" }, { X86_INS_VCVTUDQ2PS, "vcvtudq2ps" }, { X86_INS_VDIVPD, "vdivpd" }, { X86_INS_VDIVPS, "vdivps" }, { X86_INS_VDIVSD, "vdivsd" }, { X86_INS_VDIVSS, "vdivss" }, { X86_INS_VDPPD, "vdppd" }, { X86_INS_VDPPS, "vdpps" }, { X86_INS_VERR, "verr" }, { X86_INS_VERW, "verw" }, { X86_INS_VEXP2PD, "vexp2pd" }, { X86_INS_VEXP2PS, "vexp2ps" }, { X86_INS_VEXPANDPD, "vexpandpd" }, { X86_INS_VEXPANDPS, "vexpandps" }, { X86_INS_VEXTRACTF128, "vextractf128" }, { X86_INS_VEXTRACTF32X4, "vextractf32x4" }, { X86_INS_VEXTRACTF64X4, "vextractf64x4" }, { X86_INS_VEXTRACTI128, "vextracti128" }, { X86_INS_VEXTRACTI32X4, "vextracti32x4" }, { X86_INS_VEXTRACTI64X4, "vextracti64x4" }, { X86_INS_VEXTRACTPS, "vextractps" }, { X86_INS_VFMADD132PD, "vfmadd132pd" }, { X86_INS_VFMADD132PS, "vfmadd132ps" }, { X86_INS_VFMADDPD, "vfmaddpd" }, { X86_INS_VFMADD213PD, "vfmadd213pd" }, { X86_INS_VFMADD231PD, "vfmadd231pd" }, { X86_INS_VFMADDPS, "vfmaddps" }, { X86_INS_VFMADD213PS, "vfmadd213ps" }, { X86_INS_VFMADD231PS, "vfmadd231ps" }, { X86_INS_VFMADDSD, "vfmaddsd" }, { X86_INS_VFMADD213SD, "vfmadd213sd" }, { X86_INS_VFMADD132SD, "vfmadd132sd" }, { X86_INS_VFMADD231SD, "vfmadd231sd" }, { X86_INS_VFMADDSS, "vfmaddss" }, { X86_INS_VFMADD213SS, "vfmadd213ss" }, { X86_INS_VFMADD132SS, "vfmadd132ss" }, { X86_INS_VFMADD231SS, "vfmadd231ss" }, { X86_INS_VFMADDSUB132PD, "vfmaddsub132pd" }, { X86_INS_VFMADDSUB132PS, "vfmaddsub132ps" }, { X86_INS_VFMADDSUBPD, "vfmaddsubpd" }, { X86_INS_VFMADDSUB213PD, "vfmaddsub213pd" }, { X86_INS_VFMADDSUB231PD, "vfmaddsub231pd" }, { X86_INS_VFMADDSUBPS, "vfmaddsubps" }, { X86_INS_VFMADDSUB213PS, "vfmaddsub213ps" }, { X86_INS_VFMADDSUB231PS, "vfmaddsub231ps" }, { X86_INS_VFMSUB132PD, "vfmsub132pd" }, { X86_INS_VFMSUB132PS, "vfmsub132ps" }, { X86_INS_VFMSUBADD132PD, "vfmsubadd132pd" }, { X86_INS_VFMSUBADD132PS, "vfmsubadd132ps" }, { X86_INS_VFMSUBADDPD, "vfmsubaddpd" }, { X86_INS_VFMSUBADD213PD, "vfmsubadd213pd" }, { X86_INS_VFMSUBADD231PD, "vfmsubadd231pd" }, { X86_INS_VFMSUBADDPS, "vfmsubaddps" }, { X86_INS_VFMSUBADD213PS, "vfmsubadd213ps" }, { X86_INS_VFMSUBADD231PS, "vfmsubadd231ps" }, { X86_INS_VFMSUBPD, "vfmsubpd" }, { X86_INS_VFMSUB213PD, "vfmsub213pd" }, { X86_INS_VFMSUB231PD, "vfmsub231pd" }, { X86_INS_VFMSUBPS, "vfmsubps" }, { X86_INS_VFMSUB213PS, "vfmsub213ps" }, { X86_INS_VFMSUB231PS, "vfmsub231ps" }, { X86_INS_VFMSUBSD, "vfmsubsd" }, { X86_INS_VFMSUB213SD, "vfmsub213sd" }, { X86_INS_VFMSUB132SD, "vfmsub132sd" }, { X86_INS_VFMSUB231SD, "vfmsub231sd" }, { X86_INS_VFMSUBSS, "vfmsubss" }, { X86_INS_VFMSUB213SS, "vfmsub213ss" }, { X86_INS_VFMSUB132SS, "vfmsub132ss" }, { X86_INS_VFMSUB231SS, "vfmsub231ss" }, { X86_INS_VFNMADD132PD, "vfnmadd132pd" }, { X86_INS_VFNMADD132PS, "vfnmadd132ps" }, { X86_INS_VFNMADDPD, "vfnmaddpd" }, { X86_INS_VFNMADD213PD, "vfnmadd213pd" }, { X86_INS_VFNMADD231PD, "vfnmadd231pd" }, { X86_INS_VFNMADDPS, "vfnmaddps" }, { X86_INS_VFNMADD213PS, "vfnmadd213ps" }, { X86_INS_VFNMADD231PS, "vfnmadd231ps" }, { X86_INS_VFNMADDSD, "vfnmaddsd" }, { X86_INS_VFNMADD213SD, "vfnmadd213sd" }, { X86_INS_VFNMADD132SD, "vfnmadd132sd" }, { X86_INS_VFNMADD231SD, "vfnmadd231sd" }, { X86_INS_VFNMADDSS, "vfnmaddss" }, { X86_INS_VFNMADD213SS, "vfnmadd213ss" }, { X86_INS_VFNMADD132SS, "vfnmadd132ss" }, { X86_INS_VFNMADD231SS, "vfnmadd231ss" }, { X86_INS_VFNMSUB132PD, "vfnmsub132pd" }, { X86_INS_VFNMSUB132PS, "vfnmsub132ps" }, { X86_INS_VFNMSUBPD, "vfnmsubpd" }, { X86_INS_VFNMSUB213PD, "vfnmsub213pd" }, { X86_INS_VFNMSUB231PD, "vfnmsub231pd" }, { X86_INS_VFNMSUBPS, "vfnmsubps" }, { X86_INS_VFNMSUB213PS, "vfnmsub213ps" }, { X86_INS_VFNMSUB231PS, "vfnmsub231ps" }, { X86_INS_VFNMSUBSD, "vfnmsubsd" }, { X86_INS_VFNMSUB213SD, "vfnmsub213sd" }, { X86_INS_VFNMSUB132SD, "vfnmsub132sd" }, { X86_INS_VFNMSUB231SD, "vfnmsub231sd" }, { X86_INS_VFNMSUBSS, "vfnmsubss" }, { X86_INS_VFNMSUB213SS, "vfnmsub213ss" }, { X86_INS_VFNMSUB132SS, "vfnmsub132ss" }, { X86_INS_VFNMSUB231SS, "vfnmsub231ss" }, { X86_INS_VFRCZPD, "vfrczpd" }, { X86_INS_VFRCZPS, "vfrczps" }, { X86_INS_VFRCZSD, "vfrczsd" }, { X86_INS_VFRCZSS, "vfrczss" }, { X86_INS_VORPD, "vorpd" }, { X86_INS_VORPS, "vorps" }, { X86_INS_VXORPD, "vxorpd" }, { X86_INS_VXORPS, "vxorps" }, { X86_INS_VGATHERDPD, "vgatherdpd" }, { X86_INS_VGATHERDPS, "vgatherdps" }, { X86_INS_VGATHERPF0DPD, "vgatherpf0dpd" }, { X86_INS_VGATHERPF0DPS, "vgatherpf0dps" }, { X86_INS_VGATHERPF0QPD, "vgatherpf0qpd" }, { X86_INS_VGATHERPF0QPS, "vgatherpf0qps" }, { X86_INS_VGATHERPF1DPD, "vgatherpf1dpd" }, { X86_INS_VGATHERPF1DPS, "vgatherpf1dps" }, { X86_INS_VGATHERPF1QPD, "vgatherpf1qpd" }, { X86_INS_VGATHERPF1QPS, "vgatherpf1qps" }, { X86_INS_VGATHERQPD, "vgatherqpd" }, { X86_INS_VGATHERQPS, "vgatherqps" }, { X86_INS_VHADDPD, "vhaddpd" }, { X86_INS_VHADDPS, "vhaddps" }, { X86_INS_VHSUBPD, "vhsubpd" }, { X86_INS_VHSUBPS, "vhsubps" }, { X86_INS_VINSERTF128, "vinsertf128" }, { X86_INS_VINSERTF32X4, "vinsertf32x4" }, { X86_INS_VINSERTF32X8, "vinsertf32x8" }, { X86_INS_VINSERTF64X2, "vinsertf64x2" }, { X86_INS_VINSERTF64X4, "vinsertf64x4" }, { X86_INS_VINSERTI128, "vinserti128" }, { X86_INS_VINSERTI32X4, "vinserti32x4" }, { X86_INS_VINSERTI32X8, "vinserti32x8" }, { X86_INS_VINSERTI64X2, "vinserti64x2" }, { X86_INS_VINSERTI64X4, "vinserti64x4" }, { X86_INS_VINSERTPS, "vinsertps" }, { X86_INS_VLDDQU, "vlddqu" }, { X86_INS_VLDMXCSR, "vldmxcsr" }, { X86_INS_VMASKMOVDQU, "vmaskmovdqu" }, { X86_INS_VMASKMOVPD, "vmaskmovpd" }, { X86_INS_VMASKMOVPS, "vmaskmovps" }, { X86_INS_VMAXPD, "vmaxpd" }, { X86_INS_VMAXPS, "vmaxps" }, { X86_INS_VMAXSD, "vmaxsd" }, { X86_INS_VMAXSS, "vmaxss" }, { X86_INS_VMCALL, "vmcall" }, { X86_INS_VMCLEAR, "vmclear" }, { X86_INS_VMFUNC, "vmfunc" }, { X86_INS_VMINPD, "vminpd" }, { X86_INS_VMINPS, "vminps" }, { X86_INS_VMINSD, "vminsd" }, { X86_INS_VMINSS, "vminss" }, { X86_INS_VMLAUNCH, "vmlaunch" }, { X86_INS_VMLOAD, "vmload" }, { X86_INS_VMMCALL, "vmmcall" }, { X86_INS_VMOVQ, "vmovq" }, { X86_INS_VMOVDDUP, "vmovddup" }, { X86_INS_VMOVD, "vmovd" }, { X86_INS_VMOVDQA32, "vmovdqa32" }, { X86_INS_VMOVDQA64, "vmovdqa64" }, { X86_INS_VMOVDQA, "vmovdqa" }, { X86_INS_VMOVDQU16, "vmovdqu16" }, { X86_INS_VMOVDQU32, "vmovdqu32" }, { X86_INS_VMOVDQU64, "vmovdqu64" }, { X86_INS_VMOVDQU8, "vmovdqu8" }, { X86_INS_VMOVDQU, "vmovdqu" }, { X86_INS_VMOVHLPS, "vmovhlps" }, { X86_INS_VMOVHPD, "vmovhpd" }, { X86_INS_VMOVHPS, "vmovhps" }, { X86_INS_VMOVLHPS, "vmovlhps" }, { X86_INS_VMOVLPD, "vmovlpd" }, { X86_INS_VMOVLPS, "vmovlps" }, { X86_INS_VMOVMSKPD, "vmovmskpd" }, { X86_INS_VMOVMSKPS, "vmovmskps" }, { X86_INS_VMOVNTDQA, "vmovntdqa" }, { X86_INS_VMOVNTDQ, "vmovntdq" }, { X86_INS_VMOVNTPD, "vmovntpd" }, { X86_INS_VMOVNTPS, "vmovntps" }, { X86_INS_VMOVSD, "vmovsd" }, { X86_INS_VMOVSHDUP, "vmovshdup" }, { X86_INS_VMOVSLDUP, "vmovsldup" }, { X86_INS_VMOVSS, "vmovss" }, { X86_INS_VMOVUPD, "vmovupd" }, { X86_INS_VMOVUPS, "vmovups" }, { X86_INS_VMPSADBW, "vmpsadbw" }, { X86_INS_VMPTRLD, "vmptrld" }, { X86_INS_VMPTRST, "vmptrst" }, { X86_INS_VMREAD, "vmread" }, { X86_INS_VMRESUME, "vmresume" }, { X86_INS_VMRUN, "vmrun" }, { X86_INS_VMSAVE, "vmsave" }, { X86_INS_VMULPD, "vmulpd" }, { X86_INS_VMULPS, "vmulps" }, { X86_INS_VMULSD, "vmulsd" }, { X86_INS_VMULSS, "vmulss" }, { X86_INS_VMWRITE, "vmwrite" }, { X86_INS_VMXOFF, "vmxoff" }, { X86_INS_VMXON, "vmxon" }, { X86_INS_VPABSB, "vpabsb" }, { X86_INS_VPABSD, "vpabsd" }, { X86_INS_VPABSQ, "vpabsq" }, { X86_INS_VPABSW, "vpabsw" }, { X86_INS_VPACKSSDW, "vpackssdw" }, { X86_INS_VPACKSSWB, "vpacksswb" }, { X86_INS_VPACKUSDW, "vpackusdw" }, { X86_INS_VPACKUSWB, "vpackuswb" }, { X86_INS_VPADDB, "vpaddb" }, { X86_INS_VPADDD, "vpaddd" }, { X86_INS_VPADDQ, "vpaddq" }, { X86_INS_VPADDSB, "vpaddsb" }, { X86_INS_VPADDSW, "vpaddsw" }, { X86_INS_VPADDUSB, "vpaddusb" }, { X86_INS_VPADDUSW, "vpaddusw" }, { X86_INS_VPADDW, "vpaddw" }, { X86_INS_VPALIGNR, "vpalignr" }, { X86_INS_VPANDD, "vpandd" }, { X86_INS_VPANDND, "vpandnd" }, { X86_INS_VPANDNQ, "vpandnq" }, { X86_INS_VPANDN, "vpandn" }, { X86_INS_VPANDQ, "vpandq" }, { X86_INS_VPAND, "vpand" }, { X86_INS_VPAVGB, "vpavgb" }, { X86_INS_VPAVGW, "vpavgw" }, { X86_INS_VPBLENDD, "vpblendd" }, { X86_INS_VPBLENDMB, "vpblendmb" }, { X86_INS_VPBLENDMD, "vpblendmd" }, { X86_INS_VPBLENDMQ, "vpblendmq" }, { X86_INS_VPBLENDMW, "vpblendmw" }, { X86_INS_VPBLENDVB, "vpblendvb" }, { X86_INS_VPBLENDW, "vpblendw" }, { X86_INS_VPBROADCASTB, "vpbroadcastb" }, { X86_INS_VPBROADCASTD, "vpbroadcastd" }, { X86_INS_VPBROADCASTMB2Q, "vpbroadcastmb2q" }, { X86_INS_VPBROADCASTMW2D, "vpbroadcastmw2d" }, { X86_INS_VPBROADCASTQ, "vpbroadcastq" }, { X86_INS_VPBROADCASTW, "vpbroadcastw" }, { X86_INS_VPCLMULQDQ, "vpclmulqdq" }, { X86_INS_VPCMOV, "vpcmov" }, { X86_INS_VPCMPB, "vpcmpb" }, { X86_INS_VPCMPD, "vpcmpd" }, { X86_INS_VPCMPEQB, "vpcmpeqb" }, { X86_INS_VPCMPEQD, "vpcmpeqd" }, { X86_INS_VPCMPEQQ, "vpcmpeqq" }, { X86_INS_VPCMPEQW, "vpcmpeqw" }, { X86_INS_VPCMPESTRI, "vpcmpestri" }, { X86_INS_VPCMPESTRM, "vpcmpestrm" }, { X86_INS_VPCMPGTB, "vpcmpgtb" }, { X86_INS_VPCMPGTD, "vpcmpgtd" }, { X86_INS_VPCMPGTQ, "vpcmpgtq" }, { X86_INS_VPCMPGTW, "vpcmpgtw" }, { X86_INS_VPCMPISTRI, "vpcmpistri" }, { X86_INS_VPCMPISTRM, "vpcmpistrm" }, { X86_INS_VPCMPQ, "vpcmpq" }, { X86_INS_VPCMPUB, "vpcmpub" }, { X86_INS_VPCMPUD, "vpcmpud" }, { X86_INS_VPCMPUQ, "vpcmpuq" }, { X86_INS_VPCMPUW, "vpcmpuw" }, { X86_INS_VPCMPW, "vpcmpw" }, { X86_INS_VPCOMB, "vpcomb" }, { X86_INS_VPCOMD, "vpcomd" }, { X86_INS_VPCOMPRESSD, "vpcompressd" }, { X86_INS_VPCOMPRESSQ, "vpcompressq" }, { X86_INS_VPCOMQ, "vpcomq" }, { X86_INS_VPCOMUB, "vpcomub" }, { X86_INS_VPCOMUD, "vpcomud" }, { X86_INS_VPCOMUQ, "vpcomuq" }, { X86_INS_VPCOMUW, "vpcomuw" }, { X86_INS_VPCOMW, "vpcomw" }, { X86_INS_VPCONFLICTD, "vpconflictd" }, { X86_INS_VPCONFLICTQ, "vpconflictq" }, { X86_INS_VPERM2F128, "vperm2f128" }, { X86_INS_VPERM2I128, "vperm2i128" }, { X86_INS_VPERMD, "vpermd" }, { X86_INS_VPERMI2D, "vpermi2d" }, { X86_INS_VPERMI2PD, "vpermi2pd" }, { X86_INS_VPERMI2PS, "vpermi2ps" }, { X86_INS_VPERMI2Q, "vpermi2q" }, { X86_INS_VPERMIL2PD, "vpermil2pd" }, { X86_INS_VPERMIL2PS, "vpermil2ps" }, { X86_INS_VPERMILPD, "vpermilpd" }, { X86_INS_VPERMILPS, "vpermilps" }, { X86_INS_VPERMPD, "vpermpd" }, { X86_INS_VPERMPS, "vpermps" }, { X86_INS_VPERMQ, "vpermq" }, { X86_INS_VPERMT2D, "vpermt2d" }, { X86_INS_VPERMT2PD, "vpermt2pd" }, { X86_INS_VPERMT2PS, "vpermt2ps" }, { X86_INS_VPERMT2Q, "vpermt2q" }, { X86_INS_VPEXPANDD, "vpexpandd" }, { X86_INS_VPEXPANDQ, "vpexpandq" }, { X86_INS_VPEXTRB, "vpextrb" }, { X86_INS_VPEXTRD, "vpextrd" }, { X86_INS_VPEXTRQ, "vpextrq" }, { X86_INS_VPEXTRW, "vpextrw" }, { X86_INS_VPGATHERDD, "vpgatherdd" }, { X86_INS_VPGATHERDQ, "vpgatherdq" }, { X86_INS_VPGATHERQD, "vpgatherqd" }, { X86_INS_VPGATHERQQ, "vpgatherqq" }, { X86_INS_VPHADDBD, "vphaddbd" }, { X86_INS_VPHADDBQ, "vphaddbq" }, { X86_INS_VPHADDBW, "vphaddbw" }, { X86_INS_VPHADDDQ, "vphadddq" }, { X86_INS_VPHADDD, "vphaddd" }, { X86_INS_VPHADDSW, "vphaddsw" }, { X86_INS_VPHADDUBD, "vphaddubd" }, { X86_INS_VPHADDUBQ, "vphaddubq" }, { X86_INS_VPHADDUBW, "vphaddubw" }, { X86_INS_VPHADDUDQ, "vphaddudq" }, { X86_INS_VPHADDUWD, "vphadduwd" }, { X86_INS_VPHADDUWQ, "vphadduwq" }, { X86_INS_VPHADDWD, "vphaddwd" }, { X86_INS_VPHADDWQ, "vphaddwq" }, { X86_INS_VPHADDW, "vphaddw" }, { X86_INS_VPHMINPOSUW, "vphminposuw" }, { X86_INS_VPHSUBBW, "vphsubbw" }, { X86_INS_VPHSUBDQ, "vphsubdq" }, { X86_INS_VPHSUBD, "vphsubd" }, { X86_INS_VPHSUBSW, "vphsubsw" }, { X86_INS_VPHSUBWD, "vphsubwd" }, { X86_INS_VPHSUBW, "vphsubw" }, { X86_INS_VPINSRB, "vpinsrb" }, { X86_INS_VPINSRD, "vpinsrd" }, { X86_INS_VPINSRQ, "vpinsrq" }, { X86_INS_VPINSRW, "vpinsrw" }, { X86_INS_VPLZCNTD, "vplzcntd" }, { X86_INS_VPLZCNTQ, "vplzcntq" }, { X86_INS_VPMACSDD, "vpmacsdd" }, { X86_INS_VPMACSDQH, "vpmacsdqh" }, { X86_INS_VPMACSDQL, "vpmacsdql" }, { X86_INS_VPMACSSDD, "vpmacssdd" }, { X86_INS_VPMACSSDQH, "vpmacssdqh" }, { X86_INS_VPMACSSDQL, "vpmacssdql" }, { X86_INS_VPMACSSWD, "vpmacsswd" }, { X86_INS_VPMACSSWW, "vpmacssww" }, { X86_INS_VPMACSWD, "vpmacswd" }, { X86_INS_VPMACSWW, "vpmacsww" }, { X86_INS_VPMADCSSWD, "vpmadcsswd" }, { X86_INS_VPMADCSWD, "vpmadcswd" }, { X86_INS_VPMADDUBSW, "vpmaddubsw" }, { X86_INS_VPMADDWD, "vpmaddwd" }, { X86_INS_VPMASKMOVD, "vpmaskmovd" }, { X86_INS_VPMASKMOVQ, "vpmaskmovq" }, { X86_INS_VPMAXSB, "vpmaxsb" }, { X86_INS_VPMAXSD, "vpmaxsd" }, { X86_INS_VPMAXSQ, "vpmaxsq" }, { X86_INS_VPMAXSW, "vpmaxsw" }, { X86_INS_VPMAXUB, "vpmaxub" }, { X86_INS_VPMAXUD, "vpmaxud" }, { X86_INS_VPMAXUQ, "vpmaxuq" }, { X86_INS_VPMAXUW, "vpmaxuw" }, { X86_INS_VPMINSB, "vpminsb" }, { X86_INS_VPMINSD, "vpminsd" }, { X86_INS_VPMINSQ, "vpminsq" }, { X86_INS_VPMINSW, "vpminsw" }, { X86_INS_VPMINUB, "vpminub" }, { X86_INS_VPMINUD, "vpminud" }, { X86_INS_VPMINUQ, "vpminuq" }, { X86_INS_VPMINUW, "vpminuw" }, { X86_INS_VPMOVDB, "vpmovdb" }, { X86_INS_VPMOVDW, "vpmovdw" }, { X86_INS_VPMOVM2B, "vpmovm2b" }, { X86_INS_VPMOVM2D, "vpmovm2d" }, { X86_INS_VPMOVM2Q, "vpmovm2q" }, { X86_INS_VPMOVM2W, "vpmovm2w" }, { X86_INS_VPMOVMSKB, "vpmovmskb" }, { X86_INS_VPMOVQB, "vpmovqb" }, { X86_INS_VPMOVQD, "vpmovqd" }, { X86_INS_VPMOVQW, "vpmovqw" }, { X86_INS_VPMOVSDB, "vpmovsdb" }, { X86_INS_VPMOVSDW, "vpmovsdw" }, { X86_INS_VPMOVSQB, "vpmovsqb" }, { X86_INS_VPMOVSQD, "vpmovsqd" }, { X86_INS_VPMOVSQW, "vpmovsqw" }, { X86_INS_VPMOVSXBD, "vpmovsxbd" }, { X86_INS_VPMOVSXBQ, "vpmovsxbq" }, { X86_INS_VPMOVSXBW, "vpmovsxbw" }, { X86_INS_VPMOVSXDQ, "vpmovsxdq" }, { X86_INS_VPMOVSXWD, "vpmovsxwd" }, { X86_INS_VPMOVSXWQ, "vpmovsxwq" }, { X86_INS_VPMOVUSDB, "vpmovusdb" }, { X86_INS_VPMOVUSDW, "vpmovusdw" }, { X86_INS_VPMOVUSQB, "vpmovusqb" }, { X86_INS_VPMOVUSQD, "vpmovusqd" }, { X86_INS_VPMOVUSQW, "vpmovusqw" }, { X86_INS_VPMOVZXBD, "vpmovzxbd" }, { X86_INS_VPMOVZXBQ, "vpmovzxbq" }, { X86_INS_VPMOVZXBW, "vpmovzxbw" }, { X86_INS_VPMOVZXDQ, "vpmovzxdq" }, { X86_INS_VPMOVZXWD, "vpmovzxwd" }, { X86_INS_VPMOVZXWQ, "vpmovzxwq" }, { X86_INS_VPMULDQ, "vpmuldq" }, { X86_INS_VPMULHRSW, "vpmulhrsw" }, { X86_INS_VPMULHUW, "vpmulhuw" }, { X86_INS_VPMULHW, "vpmulhw" }, { X86_INS_VPMULLD, "vpmulld" }, { X86_INS_VPMULLQ, "vpmullq" }, { X86_INS_VPMULLW, "vpmullw" }, { X86_INS_VPMULUDQ, "vpmuludq" }, { X86_INS_VPORD, "vpord" }, { X86_INS_VPORQ, "vporq" }, { X86_INS_VPOR, "vpor" }, { X86_INS_VPPERM, "vpperm" }, { X86_INS_VPROTB, "vprotb" }, { X86_INS_VPROTD, "vprotd" }, { X86_INS_VPROTQ, "vprotq" }, { X86_INS_VPROTW, "vprotw" }, { X86_INS_VPSADBW, "vpsadbw" }, { X86_INS_VPSCATTERDD, "vpscatterdd" }, { X86_INS_VPSCATTERDQ, "vpscatterdq" }, { X86_INS_VPSCATTERQD, "vpscatterqd" }, { X86_INS_VPSCATTERQQ, "vpscatterqq" }, { X86_INS_VPSHAB, "vpshab" }, { X86_INS_VPSHAD, "vpshad" }, { X86_INS_VPSHAQ, "vpshaq" }, { X86_INS_VPSHAW, "vpshaw" }, { X86_INS_VPSHLB, "vpshlb" }, { X86_INS_VPSHLD, "vpshld" }, { X86_INS_VPSHLQ, "vpshlq" }, { X86_INS_VPSHLW, "vpshlw" }, { X86_INS_VPSHUFB, "vpshufb" }, { X86_INS_VPSHUFD, "vpshufd" }, { X86_INS_VPSHUFHW, "vpshufhw" }, { X86_INS_VPSHUFLW, "vpshuflw" }, { X86_INS_VPSIGNB, "vpsignb" }, { X86_INS_VPSIGND, "vpsignd" }, { X86_INS_VPSIGNW, "vpsignw" }, { X86_INS_VPSLLDQ, "vpslldq" }, { X86_INS_VPSLLD, "vpslld" }, { X86_INS_VPSLLQ, "vpsllq" }, { X86_INS_VPSLLVD, "vpsllvd" }, { X86_INS_VPSLLVQ, "vpsllvq" }, { X86_INS_VPSLLW, "vpsllw" }, { X86_INS_VPSRAD, "vpsrad" }, { X86_INS_VPSRAQ, "vpsraq" }, { X86_INS_VPSRAVD, "vpsravd" }, { X86_INS_VPSRAVQ, "vpsravq" }, { X86_INS_VPSRAW, "vpsraw" }, { X86_INS_VPSRLDQ, "vpsrldq" }, { X86_INS_VPSRLD, "vpsrld" }, { X86_INS_VPSRLQ, "vpsrlq" }, { X86_INS_VPSRLVD, "vpsrlvd" }, { X86_INS_VPSRLVQ, "vpsrlvq" }, { X86_INS_VPSRLW, "vpsrlw" }, { X86_INS_VPSUBB, "vpsubb" }, { X86_INS_VPSUBD, "vpsubd" }, { X86_INS_VPSUBQ, "vpsubq" }, { X86_INS_VPSUBSB, "vpsubsb" }, { X86_INS_VPSUBSW, "vpsubsw" }, { X86_INS_VPSUBUSB, "vpsubusb" }, { X86_INS_VPSUBUSW, "vpsubusw" }, { X86_INS_VPSUBW, "vpsubw" }, { X86_INS_VPTESTMD, "vptestmd" }, { X86_INS_VPTESTMQ, "vptestmq" }, { X86_INS_VPTESTNMD, "vptestnmd" }, { X86_INS_VPTESTNMQ, "vptestnmq" }, { X86_INS_VPTEST, "vptest" }, { X86_INS_VPUNPCKHBW, "vpunpckhbw" }, { X86_INS_VPUNPCKHDQ, "vpunpckhdq" }, { X86_INS_VPUNPCKHQDQ, "vpunpckhqdq" }, { X86_INS_VPUNPCKHWD, "vpunpckhwd" }, { X86_INS_VPUNPCKLBW, "vpunpcklbw" }, { X86_INS_VPUNPCKLDQ, "vpunpckldq" }, { X86_INS_VPUNPCKLQDQ, "vpunpcklqdq" }, { X86_INS_VPUNPCKLWD, "vpunpcklwd" }, { X86_INS_VPXORD, "vpxord" }, { X86_INS_VPXORQ, "vpxorq" }, { X86_INS_VPXOR, "vpxor" }, { X86_INS_VRCP14PD, "vrcp14pd" }, { X86_INS_VRCP14PS, "vrcp14ps" }, { X86_INS_VRCP14SD, "vrcp14sd" }, { X86_INS_VRCP14SS, "vrcp14ss" }, { X86_INS_VRCP28PD, "vrcp28pd" }, { X86_INS_VRCP28PS, "vrcp28ps" }, { X86_INS_VRCP28SD, "vrcp28sd" }, { X86_INS_VRCP28SS, "vrcp28ss" }, { X86_INS_VRCPPS, "vrcpps" }, { X86_INS_VRCPSS, "vrcpss" }, { X86_INS_VRNDSCALEPD, "vrndscalepd" }, { X86_INS_VRNDSCALEPS, "vrndscaleps" }, { X86_INS_VRNDSCALESD, "vrndscalesd" }, { X86_INS_VRNDSCALESS, "vrndscaless" }, { X86_INS_VROUNDPD, "vroundpd" }, { X86_INS_VROUNDPS, "vroundps" }, { X86_INS_VROUNDSD, "vroundsd" }, { X86_INS_VROUNDSS, "vroundss" }, { X86_INS_VRSQRT14PD, "vrsqrt14pd" }, { X86_INS_VRSQRT14PS, "vrsqrt14ps" }, { X86_INS_VRSQRT14SD, "vrsqrt14sd" }, { X86_INS_VRSQRT14SS, "vrsqrt14ss" }, { X86_INS_VRSQRT28PD, "vrsqrt28pd" }, { X86_INS_VRSQRT28PS, "vrsqrt28ps" }, { X86_INS_VRSQRT28SD, "vrsqrt28sd" }, { X86_INS_VRSQRT28SS, "vrsqrt28ss" }, { X86_INS_VRSQRTPS, "vrsqrtps" }, { X86_INS_VRSQRTSS, "vrsqrtss" }, { X86_INS_VSCATTERDPD, "vscatterdpd" }, { X86_INS_VSCATTERDPS, "vscatterdps" }, { X86_INS_VSCATTERPF0DPD, "vscatterpf0dpd" }, { X86_INS_VSCATTERPF0DPS, "vscatterpf0dps" }, { X86_INS_VSCATTERPF0QPD, "vscatterpf0qpd" }, { X86_INS_VSCATTERPF0QPS, "vscatterpf0qps" }, { X86_INS_VSCATTERPF1DPD, "vscatterpf1dpd" }, { X86_INS_VSCATTERPF1DPS, "vscatterpf1dps" }, { X86_INS_VSCATTERPF1QPD, "vscatterpf1qpd" }, { X86_INS_VSCATTERPF1QPS, "vscatterpf1qps" }, { X86_INS_VSCATTERQPD, "vscatterqpd" }, { X86_INS_VSCATTERQPS, "vscatterqps" }, { X86_INS_VSHUFPD, "vshufpd" }, { X86_INS_VSHUFPS, "vshufps" }, { X86_INS_VSQRTPD, "vsqrtpd" }, { X86_INS_VSQRTPS, "vsqrtps" }, { X86_INS_VSQRTSD, "vsqrtsd" }, { X86_INS_VSQRTSS, "vsqrtss" }, { X86_INS_VSTMXCSR, "vstmxcsr" }, { X86_INS_VSUBPD, "vsubpd" }, { X86_INS_VSUBPS, "vsubps" }, { X86_INS_VSUBSD, "vsubsd" }, { X86_INS_VSUBSS, "vsubss" }, { X86_INS_VTESTPD, "vtestpd" }, { X86_INS_VTESTPS, "vtestps" }, { X86_INS_VUNPCKHPD, "vunpckhpd" }, { X86_INS_VUNPCKHPS, "vunpckhps" }, { X86_INS_VUNPCKLPD, "vunpcklpd" }, { X86_INS_VUNPCKLPS, "vunpcklps" }, { X86_INS_VZEROALL, "vzeroall" }, { X86_INS_VZEROUPPER, "vzeroupper" }, { X86_INS_WAIT, "wait" }, { X86_INS_WBINVD, "wbinvd" }, { X86_INS_WRFSBASE, "wrfsbase" }, { X86_INS_WRGSBASE, "wrgsbase" }, { X86_INS_WRMSR, "wrmsr" }, { X86_INS_XABORT, "xabort" }, { X86_INS_XACQUIRE, "xacquire" }, { X86_INS_XBEGIN, "xbegin" }, { X86_INS_XCHG, "xchg" }, { X86_INS_XCRYPTCBC, "xcryptcbc" }, { X86_INS_XCRYPTCFB, "xcryptcfb" }, { X86_INS_XCRYPTCTR, "xcryptctr" }, { X86_INS_XCRYPTECB, "xcryptecb" }, { X86_INS_XCRYPTOFB, "xcryptofb" }, { X86_INS_XEND, "xend" }, { X86_INS_XGETBV, "xgetbv" }, { X86_INS_XLATB, "xlatb" }, { X86_INS_XRELEASE, "xrelease" }, { X86_INS_XRSTOR, "xrstor" }, { X86_INS_XRSTOR64, "xrstor64" }, { X86_INS_XRSTORS, "xrstors" }, { X86_INS_XRSTORS64, "xrstors64" }, { X86_INS_XSAVE, "xsave" }, { X86_INS_XSAVE64, "xsave64" }, { X86_INS_XSAVEC, "xsavec" }, { X86_INS_XSAVEC64, "xsavec64" }, { X86_INS_XSAVEOPT, "xsaveopt" }, { X86_INS_XSAVEOPT64, "xsaveopt64" }, { X86_INS_XSAVES, "xsaves" }, { X86_INS_XSAVES64, "xsaves64" }, { X86_INS_XSETBV, "xsetbv" }, { X86_INS_XSHA1, "xsha1" }, { X86_INS_XSHA256, "xsha256" }, { X86_INS_XSTORE, "xstore" }, { X86_INS_XTEST, "xtest" }, { X86_INS_FDISI8087_NOP, "fdisi8087_nop" }, { X86_INS_FENI8087_NOP, "feni8087_nop" }, // pseudo instructions { X86_INS_CMPSS, "cmpss" }, { X86_INS_CMPEQSS, "cmpeqss" }, { X86_INS_CMPLTSS, "cmpltss" }, { X86_INS_CMPLESS, "cmpless" }, { X86_INS_CMPUNORDSS, "cmpunordss" }, { X86_INS_CMPNEQSS, "cmpneqss" }, { X86_INS_CMPNLTSS, "cmpnltss" }, { X86_INS_CMPNLESS, "cmpnless" }, { X86_INS_CMPORDSS, "cmpordss" }, { X86_INS_CMPSD, "cmpsd" }, { X86_INS_CMPEQSD, "cmpeqsd" }, { X86_INS_CMPLTSD, "cmpltsd" }, { X86_INS_CMPLESD, "cmplesd" }, { X86_INS_CMPUNORDSD, "cmpunordsd" }, { X86_INS_CMPNEQSD, "cmpneqsd" }, { X86_INS_CMPNLTSD, "cmpnltsd" }, { X86_INS_CMPNLESD, "cmpnlesd" }, { X86_INS_CMPORDSD, "cmpordsd" }, { X86_INS_CMPPS, "cmpps" }, { X86_INS_CMPEQPS, "cmpeqps" }, { X86_INS_CMPLTPS, "cmpltps" }, { X86_INS_CMPLEPS, "cmpleps" }, { X86_INS_CMPUNORDPS, "cmpunordps" }, { X86_INS_CMPNEQPS, "cmpneqps" }, { X86_INS_CMPNLTPS, "cmpnltps" }, { X86_INS_CMPNLEPS, "cmpnleps" }, { X86_INS_CMPORDPS, "cmpordps" }, { X86_INS_CMPPD, "cmppd" }, { X86_INS_CMPEQPD, "cmpeqpd" }, { X86_INS_CMPLTPD, "cmpltpd" }, { X86_INS_CMPLEPD, "cmplepd" }, { X86_INS_CMPUNORDPD, "cmpunordpd" }, { X86_INS_CMPNEQPD, "cmpneqpd" }, { X86_INS_CMPNLTPD, "cmpnltpd" }, { X86_INS_CMPNLEPD, "cmpnlepd" }, { X86_INS_CMPORDPD, "cmpordpd" }, { X86_INS_VCMPSS, "vcmpss" }, { X86_INS_VCMPEQSS, "vcmpeqss" }, { X86_INS_VCMPLTSS, "vcmpltss" }, { X86_INS_VCMPLESS, "vcmpless" }, { X86_INS_VCMPUNORDSS, "vcmpunordss" }, { X86_INS_VCMPNEQSS, "vcmpneqss" }, { X86_INS_VCMPNLTSS, "vcmpnltss" }, { X86_INS_VCMPNLESS, "vcmpnless" }, { X86_INS_VCMPORDSS, "vcmpordss" }, { X86_INS_VCMPEQ_UQSS, "vcmpeq_uqss" }, { X86_INS_VCMPNGESS, "vcmpngess" }, { X86_INS_VCMPNGTSS, "vcmpngtss" }, { X86_INS_VCMPFALSESS, "vcmpfalsess" }, { X86_INS_VCMPNEQ_OQSS, "vcmpneq_oqss" }, { X86_INS_VCMPGESS, "vcmpgess" }, { X86_INS_VCMPGTSS, "vcmpgtss" }, { X86_INS_VCMPTRUESS, "vcmptruess" }, { X86_INS_VCMPEQ_OSSS, "vcmpeq_osss" }, { X86_INS_VCMPLT_OQSS, "vcmplt_oqss" }, { X86_INS_VCMPLE_OQSS, "vcmple_oqss" }, { X86_INS_VCMPUNORD_SSS, "vcmpunord_sss" }, { X86_INS_VCMPNEQ_USSS, "vcmpneq_usss" }, { X86_INS_VCMPNLT_UQSS, "vcmpnlt_uqss" }, { X86_INS_VCMPNLE_UQSS, "vcmpnle_uqss" }, { X86_INS_VCMPORD_SSS, "vcmpord_sss" }, { X86_INS_VCMPEQ_USSS, "vcmpeq_usss" }, { X86_INS_VCMPNGE_UQSS, "vcmpnge_uqss" }, { X86_INS_VCMPNGT_UQSS, "vcmpngt_uqss" }, { X86_INS_VCMPFALSE_OSSS, "vcmpfalse_osss" }, { X86_INS_VCMPNEQ_OSSS, "vcmpneq_osss" }, { X86_INS_VCMPGE_OQSS, "vcmpge_oqss" }, { X86_INS_VCMPGT_OQSS, "vcmpgt_oqss" }, { X86_INS_VCMPTRUE_USSS, "vcmptrue_usss" }, { X86_INS_VCMPSD, "vcmpsd" }, { X86_INS_VCMPEQSD, "vcmpeqsd" }, { X86_INS_VCMPLTSD, "vcmpltsd" }, { X86_INS_VCMPLESD, "vcmplesd" }, { X86_INS_VCMPUNORDSD, "vcmpunordsd" }, { X86_INS_VCMPNEQSD, "vcmpneqsd" }, { X86_INS_VCMPNLTSD, "vcmpnltsd" }, { X86_INS_VCMPNLESD, "vcmpnlesd" }, { X86_INS_VCMPORDSD, "vcmpordsd" }, { X86_INS_VCMPEQ_UQSD, "vcmpeq_uqsd" }, { X86_INS_VCMPNGESD, "vcmpngesd" }, { X86_INS_VCMPNGTSD, "vcmpngtsd" }, { X86_INS_VCMPFALSESD, "vcmpfalsesd" }, { X86_INS_VCMPNEQ_OQSD, "vcmpneq_oqsd" }, { X86_INS_VCMPGESD, "vcmpgesd" }, { X86_INS_VCMPGTSD, "vcmpgtsd" }, { X86_INS_VCMPTRUESD, "vcmptruesd" }, { X86_INS_VCMPEQ_OSSD, "vcmpeq_ossd" }, { X86_INS_VCMPLT_OQSD, "vcmplt_oqsd" }, { X86_INS_VCMPLE_OQSD, "vcmple_oqsd" }, { X86_INS_VCMPUNORD_SSD, "vcmpunord_ssd" }, { X86_INS_VCMPNEQ_USSD, "vcmpneq_ussd" }, { X86_INS_VCMPNLT_UQSD, "vcmpnlt_uqsd" }, { X86_INS_VCMPNLE_UQSD, "vcmpnle_uqsd" }, { X86_INS_VCMPORD_SSD, "vcmpord_ssd" }, { X86_INS_VCMPEQ_USSD, "vcmpeq_ussd" }, { X86_INS_VCMPNGE_UQSD, "vcmpnge_uqsd" }, { X86_INS_VCMPNGT_UQSD, "vcmpngt_uqsd" }, { X86_INS_VCMPFALSE_OSSD, "vcmpfalse_ossd" }, { X86_INS_VCMPNEQ_OSSD, "vcmpneq_ossd" }, { X86_INS_VCMPGE_OQSD, "vcmpge_oqsd" }, { X86_INS_VCMPGT_OQSD, "vcmpgt_oqsd" }, { X86_INS_VCMPTRUE_USSD, "vcmptrue_ussd" }, { X86_INS_VCMPPS, "vcmpps" }, { X86_INS_VCMPEQPS, "vcmpeqps" }, { X86_INS_VCMPLTPS, "vcmpltps" }, { X86_INS_VCMPLEPS, "vcmpleps" }, { X86_INS_VCMPUNORDPS, "vcmpunordps" }, { X86_INS_VCMPNEQPS, "vcmpneqps" }, { X86_INS_VCMPNLTPS, "vcmpnltps" }, { X86_INS_VCMPNLEPS, "vcmpnleps" }, { X86_INS_VCMPORDPS, "vcmpordps" }, { X86_INS_VCMPEQ_UQPS, "vcmpeq_uqps" }, { X86_INS_VCMPNGEPS, "vcmpngeps" }, { X86_INS_VCMPNGTPS, "vcmpngtps" }, { X86_INS_VCMPFALSEPS, "vcmpfalseps" }, { X86_INS_VCMPNEQ_OQPS, "vcmpneq_oqps" }, { X86_INS_VCMPGEPS, "vcmpgeps" }, { X86_INS_VCMPGTPS, "vcmpgtps" }, { X86_INS_VCMPTRUEPS, "vcmptrueps" }, { X86_INS_VCMPEQ_OSPS, "vcmpeq_osps" }, { X86_INS_VCMPLT_OQPS, "vcmplt_oqps" }, { X86_INS_VCMPLE_OQPS, "vcmple_oqps" }, { X86_INS_VCMPUNORD_SPS, "vcmpunord_sps" }, { X86_INS_VCMPNEQ_USPS, "vcmpneq_usps" }, { X86_INS_VCMPNLT_UQPS, "vcmpnlt_uqps" }, { X86_INS_VCMPNLE_UQPS, "vcmpnle_uqps" }, { X86_INS_VCMPORD_SPS, "vcmpord_sps" }, { X86_INS_VCMPEQ_USPS, "vcmpeq_usps" }, { X86_INS_VCMPNGE_UQPS, "vcmpnge_uqps" }, { X86_INS_VCMPNGT_UQPS, "vcmpngt_uqps" }, { X86_INS_VCMPFALSE_OSPS, "vcmpfalse_osps" }, { X86_INS_VCMPNEQ_OSPS, "vcmpneq_osps" }, { X86_INS_VCMPGE_OQPS, "vcmpge_oqps" }, { X86_INS_VCMPGT_OQPS, "vcmpgt_oqps" }, { X86_INS_VCMPTRUE_USPS, "vcmptrue_usps" }, { X86_INS_VCMPPD, "vcmppd" }, { X86_INS_VCMPEQPD, "vcmpeqpd" }, { X86_INS_VCMPLTPD, "vcmpltpd" }, { X86_INS_VCMPLEPD, "vcmplepd" }, { X86_INS_VCMPUNORDPD, "vcmpunordpd" }, { X86_INS_VCMPNEQPD, "vcmpneqpd" }, { X86_INS_VCMPNLTPD, "vcmpnltpd" }, { X86_INS_VCMPNLEPD, "vcmpnlepd" }, { X86_INS_VCMPORDPD, "vcmpordpd" }, { X86_INS_VCMPEQ_UQPD, "vcmpeq_uqpd" }, { X86_INS_VCMPNGEPD, "vcmpngepd" }, { X86_INS_VCMPNGTPD, "vcmpngtpd" }, { X86_INS_VCMPFALSEPD, "vcmpfalsepd" }, { X86_INS_VCMPNEQ_OQPD, "vcmpneq_oqpd" }, { X86_INS_VCMPGEPD, "vcmpgepd" }, { X86_INS_VCMPGTPD, "vcmpgtpd" }, { X86_INS_VCMPTRUEPD, "vcmptruepd" }, { X86_INS_VCMPEQ_OSPD, "vcmpeq_ospd" }, { X86_INS_VCMPLT_OQPD, "vcmplt_oqpd" }, { X86_INS_VCMPLE_OQPD, "vcmple_oqpd" }, { X86_INS_VCMPUNORD_SPD, "vcmpunord_spd" }, { X86_INS_VCMPNEQ_USPD, "vcmpneq_uspd" }, { X86_INS_VCMPNLT_UQPD, "vcmpnlt_uqpd" }, { X86_INS_VCMPNLE_UQPD, "vcmpnle_uqpd" }, { X86_INS_VCMPORD_SPD, "vcmpord_spd" }, { X86_INS_VCMPEQ_USPD, "vcmpeq_uspd" }, { X86_INS_VCMPNGE_UQPD, "vcmpnge_uqpd" }, { X86_INS_VCMPNGT_UQPD, "vcmpngt_uqpd" }, { X86_INS_VCMPFALSE_OSPD, "vcmpfalse_ospd" }, { X86_INS_VCMPNEQ_OSPD, "vcmpneq_ospd" }, { X86_INS_VCMPGE_OQPD, "vcmpge_oqpd" }, { X86_INS_VCMPGT_OQPD, "vcmpgt_oqpd" }, { X86_INS_VCMPTRUE_USPD, "vcmptrue_uspd" }, }; #endif const char *X86_insn_name(csh handle, unsigned int id) { #ifndef CAPSTONE_DIET if (id >= X86_INS_ENDING) return NULL; return insn_name_maps[id].name; #else return NULL; #endif } #ifndef CAPSTONE_DIET static name_map group_name_maps[] = { // generic groups { X86_GRP_INVALID, NULL }, { X86_GRP_JUMP, "jump" }, { X86_GRP_CALL, "call" }, { X86_GRP_RET, "ret" }, { X86_GRP_INT, "int" }, { X86_GRP_IRET, "iret" }, { X86_GRP_PRIVILEGE, "privilege" }, // architecture-specific groups { X86_GRP_VM, "vm" }, { X86_GRP_3DNOW, "3dnow" }, { X86_GRP_AES, "aes" }, { X86_GRP_ADX, "adx" }, { X86_GRP_AVX, "avx" }, { X86_GRP_AVX2, "avx2" }, { X86_GRP_AVX512, "avx512" }, { X86_GRP_BMI, "bmi" }, { X86_GRP_BMI2, "bmi2" }, { X86_GRP_CMOV, "cmov" }, { X86_GRP_F16C, "fc16" }, { X86_GRP_FMA, "fma" }, { X86_GRP_FMA4, "fma4" }, { X86_GRP_FSGSBASE, "fsgsbase" }, { X86_GRP_HLE, "hle" }, { X86_GRP_MMX, "mmx" }, { X86_GRP_MODE32, "mode32" }, { X86_GRP_MODE64, "mode64" }, { X86_GRP_RTM, "rtm" }, { X86_GRP_SHA, "sha" }, { X86_GRP_SSE1, "sse1" }, { X86_GRP_SSE2, "sse2" }, { X86_GRP_SSE3, "sse3" }, { X86_GRP_SSE41, "sse41" }, { X86_GRP_SSE42, "sse42" }, { X86_GRP_SSE4A, "sse4a" }, { X86_GRP_SSSE3, "ssse3" }, { X86_GRP_PCLMUL, "pclmul" }, { X86_GRP_XOP, "xop" }, { X86_GRP_CDI, "cdi" }, { X86_GRP_ERI, "eri" }, { X86_GRP_TBM, "tbm" }, { X86_GRP_16BITMODE, "16bitmode" }, { X86_GRP_NOT64BITMODE, "not64bitmode" }, { X86_GRP_SGX, "sgx" }, { X86_GRP_DQI, "dqi" }, { X86_GRP_BWI, "bwi" }, { X86_GRP_PFI, "pfi" }, { X86_GRP_VLX, "vlx" }, { X86_GRP_SMAP, "smap" }, { X86_GRP_NOVLX, "novlx" }, }; #endif const char *X86_group_name(csh handle, unsigned int id) { #ifndef CAPSTONE_DIET return id2name(group_name_maps, ARR_SIZE(group_name_maps), id); #else return NULL; #endif } #define GET_INSTRINFO_ENUM #ifdef CAPSTONE_X86_REDUCE #include "X86GenInstrInfo_reduce.inc" #else #include "X86GenInstrInfo.inc" #endif #ifndef CAPSTONE_X86_REDUCE static insn_map insns[] = { // full x86 instructions // dummy item { 0, 0, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, #include "X86MappingInsn.inc" }; #else // X86 reduce (defined CAPSTONE_X86_REDUCE) static insn_map insns[] = { // reduce x86 instructions // dummy item { 0, 0, #ifndef CAPSTONE_DIET { 0 }, { 0 }, { 0 }, 0, 0 #endif }, #include "X86MappingInsn_reduce.inc" }; #endif #ifndef CAPSTONE_DIET // replace r1 = r2 static void arr_replace(uint16_t *arr, uint8_t max, x86_reg r1, x86_reg r2) { uint8_t i; for(i = 0; i < max; i++) { if (arr[i] == r1) { arr[i] = r2; break; } } } #endif // given internal insn id, return public instruction info void X86_get_insn_id(cs_struct *h, cs_insn *insn, unsigned int id) { int i = insn_find(insns, ARR_SIZE(insns), id, &h->insn_cache); if (i != 0) { insn->id = insns[i].mapid; if (h->detail) { #ifndef CAPSTONE_DIET memcpy(insn->detail->regs_read, insns[i].regs_use, sizeof(insns[i].regs_use)); insn->detail->regs_read_count = (uint8_t)count_positive(insns[i].regs_use); // special cases when regs_write[] depends on arch switch(id) { default: memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod)); insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod); break; case X86_RDTSC: if (h->mode == CS_MODE_64) { memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod)); insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod); } else { insn->detail->regs_write[0] = X86_REG_EAX; insn->detail->regs_write[1] = X86_REG_EDX; insn->detail->regs_write_count = 2; } break; case X86_RDTSCP: if (h->mode == CS_MODE_64) { memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod)); insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod); } else { insn->detail->regs_write[0] = X86_REG_EAX; insn->detail->regs_write[1] = X86_REG_ECX; insn->detail->regs_write[2] = X86_REG_EDX; insn->detail->regs_write_count = 3; } break; } switch(insn->id) { default: break; case X86_INS_LOOP: case X86_INS_LOOPE: case X86_INS_LOOPNE: switch(h->mode) { default: break; case CS_MODE_16: insn->detail->regs_read[0] = X86_REG_CX; insn->detail->regs_read_count = 1; insn->detail->regs_write[0] = X86_REG_CX; insn->detail->regs_write_count = 1; break; case CS_MODE_32: insn->detail->regs_read[0] = X86_REG_ECX; insn->detail->regs_read_count = 1; insn->detail->regs_write[0] = X86_REG_ECX; insn->detail->regs_write_count = 1; break; case CS_MODE_64: insn->detail->regs_read[0] = X86_REG_RCX; insn->detail->regs_read_count = 1; insn->detail->regs_write[0] = X86_REG_RCX; insn->detail->regs_write_count = 1; break; } // LOOPE & LOOPNE also read EFLAGS if (insn->id != X86_INS_LOOP) { insn->detail->regs_read[1] = X86_REG_EFLAGS; insn->detail->regs_read_count = 2; } break; case X86_INS_LODSB: case X86_INS_LODSD: case X86_INS_LODSQ: case X86_INS_LODSW: switch(h->mode) { default: break; case CS_MODE_16: arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_SI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_SI); break; case CS_MODE_64: arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_RSI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_RSI); break; } break; case X86_INS_SCASB: case X86_INS_SCASW: case X86_INS_SCASQ: case X86_INS_STOSB: case X86_INS_STOSD: case X86_INS_STOSQ: case X86_INS_STOSW: switch(h->mode) { default: break; case CS_MODE_16: arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_DI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_DI); break; case CS_MODE_64: arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_RDI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_RDI); break; } break; case X86_INS_CMPSB: case X86_INS_CMPSD: case X86_INS_CMPSQ: case X86_INS_CMPSW: case X86_INS_MOVSB: case X86_INS_MOVSW: case X86_INS_MOVSD: case X86_INS_MOVSQ: switch(h->mode) { default: break; case CS_MODE_16: arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_DI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_DI); arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_SI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_SI); break; case CS_MODE_64: arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_RDI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_RDI); arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_RSI); arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_RSI); break; } break; } memcpy(insn->detail->groups, insns[i].groups, sizeof(insns[i].groups)); insn->detail->groups_count = (uint8_t)count_positive8(insns[i].groups); if (insns[i].branch || insns[i].indirect_branch) { // this insn also belongs to JUMP group. add JUMP group insn->detail->groups[insn->detail->groups_count] = X86_GRP_JUMP; insn->detail->groups_count++; } switch (insns[i].id) { case X86_OUT8ir: case X86_OUT16ir: case X86_OUT32ir: if (insn->detail->x86.operands[0].imm == -78) { // Writing to port 0xb2 causes an SMI on most platforms // See: http://cs.gmu.edu/~tr-admin/papers/GMU-CS-TR-2011-8.pdf insn->detail->groups[insn->detail->groups_count] = X86_GRP_INT; insn->detail->groups_count++; } break; default: break; } #endif } } } // map special instructions with accumulate registers. // this is needed because LLVM embeds these register names into AsmStrs[], // but not separately in operands struct insn_reg { uint16_t insn; x86_reg reg; enum cs_ac_type access; }; struct insn_reg2 { uint16_t insn; x86_reg reg1, reg2; enum cs_ac_type access1, access2; }; static struct insn_reg insn_regs_att[] = { { X86_INSB, X86_REG_DX }, { X86_INSW, X86_REG_DX }, { X86_INSL, X86_REG_DX }, { X86_MOV64o64a, X86_REG_RAX }, { X86_MOV32o32a, X86_REG_EAX }, { X86_MOV64o32a, X86_REG_EAX }, { X86_MOV16o16a, X86_REG_AX }, { X86_PUSHCS32, X86_REG_CS }, { X86_PUSHDS32, X86_REG_DS }, { X86_PUSHES32, X86_REG_ES }, { X86_PUSHFS32, X86_REG_FS }, { X86_PUSHGS32, X86_REG_GS }, { X86_PUSHSS32, X86_REG_SS }, { X86_PUSHFS64, X86_REG_FS }, { X86_PUSHGS64, X86_REG_GS }, { X86_PUSHCS16, X86_REG_CS }, { X86_PUSHDS16, X86_REG_DS }, { X86_PUSHES16, X86_REG_ES }, { X86_PUSHFS16, X86_REG_FS }, { X86_PUSHGS16, X86_REG_GS }, { X86_PUSHSS16, X86_REG_SS }, { X86_POPDS32, X86_REG_DS }, { X86_POPES32, X86_REG_ES }, { X86_POPFS32, X86_REG_FS }, { X86_POPGS32, X86_REG_GS }, { X86_POPSS32, X86_REG_SS }, { X86_POPFS64, X86_REG_FS }, { X86_POPGS64, X86_REG_GS }, { X86_POPDS16, X86_REG_DS }, { X86_POPES16, X86_REG_ES }, { X86_POPFS16, X86_REG_FS }, { X86_POPGS16, X86_REG_GS }, { X86_POPSS16, X86_REG_SS }, { X86_RCL32rCL, X86_REG_CL }, { X86_SHL8rCL, X86_REG_CL }, { X86_SHL16rCL, X86_REG_CL }, { X86_SHL32rCL, X86_REG_CL }, { X86_SHL64rCL, X86_REG_CL }, { X86_SAL8rCL, X86_REG_CL }, { X86_SAL16rCL, X86_REG_CL }, { X86_SAL32rCL, X86_REG_CL }, { X86_SAL64rCL, X86_REG_CL }, { X86_SHR8rCL, X86_REG_CL }, { X86_SHR16rCL, X86_REG_CL }, { X86_SHR32rCL, X86_REG_CL }, { X86_SHR64rCL, X86_REG_CL }, { X86_SAR8rCL, X86_REG_CL }, { X86_SAR16rCL, X86_REG_CL }, { X86_SAR32rCL, X86_REG_CL }, { X86_SAR64rCL, X86_REG_CL }, { X86_RCL8rCL, X86_REG_CL }, { X86_RCL16rCL, X86_REG_CL }, { X86_RCL32rCL, X86_REG_CL }, { X86_RCL64rCL, X86_REG_CL }, { X86_RCR8rCL, X86_REG_CL }, { X86_RCR16rCL, X86_REG_CL }, { X86_RCR32rCL, X86_REG_CL }, { X86_RCR64rCL, X86_REG_CL }, { X86_ROL8rCL, X86_REG_CL }, { X86_ROL16rCL, X86_REG_CL }, { X86_ROL32rCL, X86_REG_CL }, { X86_ROL64rCL, X86_REG_CL }, { X86_ROR8rCL, X86_REG_CL }, { X86_ROR16rCL, X86_REG_CL }, { X86_ROR32rCL, X86_REG_CL }, { X86_ROR64rCL, X86_REG_CL }, { X86_SHLD16rrCL, X86_REG_CL }, { X86_SHRD16rrCL, X86_REG_CL }, { X86_SHLD32rrCL, X86_REG_CL }, { X86_SHRD32rrCL, X86_REG_CL }, { X86_SHLD64rrCL, X86_REG_CL }, { X86_SHRD64rrCL, X86_REG_CL }, { X86_SHLD16mrCL, X86_REG_CL }, { X86_SHRD16mrCL, X86_REG_CL }, { X86_SHLD32mrCL, X86_REG_CL }, { X86_SHRD32mrCL, X86_REG_CL }, { X86_SHLD64mrCL, X86_REG_CL }, { X86_SHRD64mrCL, X86_REG_CL }, { X86_OUT8ir, X86_REG_AL }, { X86_OUT16ir, X86_REG_AX }, { X86_OUT32ir, X86_REG_EAX }, #ifndef CAPSTONE_X86_REDUCE { X86_SKINIT, X86_REG_EAX }, { X86_VMRUN32, X86_REG_EAX }, { X86_VMRUN64, X86_REG_RAX }, { X86_VMLOAD32, X86_REG_EAX }, { X86_VMLOAD64, X86_REG_RAX }, { X86_VMSAVE32, X86_REG_EAX }, { X86_VMSAVE64, X86_REG_RAX }, { X86_FNSTSW16r, X86_REG_AX }, { X86_ADD_FrST0, X86_REG_ST0 }, { X86_SUB_FrST0, X86_REG_ST0 }, { X86_SUBR_FrST0, X86_REG_ST0 }, { X86_MUL_FrST0, X86_REG_ST0 }, { X86_DIV_FrST0, X86_REG_ST0 }, { X86_DIVR_FrST0, X86_REG_ST0 }, #endif }; static struct insn_reg insn_regs_intel[] = { { X86_OUTSB, X86_REG_DX, CS_AC_WRITE }, { X86_OUTSW, X86_REG_DX, CS_AC_WRITE }, { X86_OUTSL, X86_REG_DX, CS_AC_WRITE }, { X86_MOV8ao16, X86_REG_AL, CS_AC_WRITE }, // 16-bit A0 1020 // mov al, byte ptr [0x2010] { X86_MOV8ao32, X86_REG_AL, CS_AC_WRITE }, // 32-bit A0 10203040 // mov al, byte ptr [0x40302010] { X86_MOV8ao64, X86_REG_AL, CS_AC_WRITE }, // 64-bit 66 A0 1020304050607080 // movabs al, byte ptr [0x8070605040302010] { X86_MOV16ao16, X86_REG_AX, CS_AC_WRITE }, // 16-bit A1 1020 // mov ax, word ptr [0x2010] { X86_MOV16ao32, X86_REG_AX, CS_AC_WRITE }, // 32-bit A1 10203040 // mov ax, word ptr [0x40302010] { X86_MOV16ao64, X86_REG_AX, CS_AC_WRITE }, // 64-bit 66 A1 1020304050607080 // movabs ax, word ptr [0x8070605040302010] { X86_MOV32ao16, X86_REG_EAX, CS_AC_WRITE }, // 32-bit 67 A1 1020 // mov eax, dword ptr [0x2010] { X86_MOV32ao32, X86_REG_EAX, CS_AC_WRITE }, // 32-bit A1 10203040 // mov eax, dword ptr [0x40302010] { X86_MOV32ao64, X86_REG_EAX, CS_AC_WRITE }, // 64-bit A1 1020304050607080 // movabs eax, dword ptr [0x8070605040302010] { X86_MOV64ao32, X86_REG_RAX, CS_AC_WRITE }, // 64-bit 48 8B04 10203040 // mov rax, qword ptr [0x40302010] { X86_MOV64ao64, X86_REG_RAX, CS_AC_WRITE }, // 64-bit 48 A1 1020304050607080 // movabs rax, qword ptr [0x8070605040302010] { X86_LODSQ, X86_REG_RAX, CS_AC_WRITE }, { X86_OR32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_SUB32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_TEST32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_ADD32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_XCHG64ar, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_LODSB, X86_REG_AL, CS_AC_WRITE }, { X86_AND32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_IN16ri, X86_REG_AX, CS_AC_WRITE }, { X86_CMP64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_XOR32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_XCHG16ar, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_LODSW, X86_REG_AX, CS_AC_WRITE }, { X86_AND16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_ADC16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_XCHG32ar64, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_ADC8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_CMP32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_AND8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_SCASW, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_XOR8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_SUB16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_OR16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_XCHG32ar, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_SBB8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_SCASQ, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_SBB32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_XOR64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_SUB64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_ADD64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_OR8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_TEST64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_SBB16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_TEST8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_IN8ri, X86_REG_AL, CS_AC_WRITE }, { X86_TEST16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_SCASL, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_SUB8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_ADD8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_OR64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_SCASB, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_SBB64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_ADD16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_XOR16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_AND64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_LODSL, X86_REG_EAX, CS_AC_WRITE }, { X86_CMP8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ }, { X86_ADC64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ }, { X86_CMP16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ }, { X86_ADC32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ }, { X86_IN32ri, X86_REG_EAX, CS_AC_WRITE }, { X86_PUSHCS32, X86_REG_CS, CS_AC_READ }, { X86_PUSHDS32, X86_REG_DS, CS_AC_READ }, { X86_PUSHES32, X86_REG_ES, CS_AC_READ }, { X86_PUSHFS32, X86_REG_FS, CS_AC_READ }, { X86_PUSHGS32, X86_REG_GS, CS_AC_READ }, { X86_PUSHSS32, X86_REG_SS, CS_AC_READ }, { X86_PUSHFS64, X86_REG_FS, CS_AC_READ }, { X86_PUSHGS64, X86_REG_GS, CS_AC_READ }, { X86_PUSHCS16, X86_REG_CS, CS_AC_READ }, { X86_PUSHDS16, X86_REG_DS, CS_AC_READ }, { X86_PUSHES16, X86_REG_ES, CS_AC_READ }, { X86_PUSHFS16, X86_REG_FS, CS_AC_READ }, { X86_PUSHGS16, X86_REG_GS, CS_AC_READ }, { X86_PUSHSS16, X86_REG_SS, CS_AC_READ }, { X86_POPDS32, X86_REG_DS, CS_AC_WRITE }, { X86_POPES32, X86_REG_ES, CS_AC_WRITE }, { X86_POPFS32, X86_REG_FS, CS_AC_WRITE }, { X86_POPGS32, X86_REG_GS, CS_AC_WRITE }, { X86_POPSS32, X86_REG_SS, CS_AC_WRITE }, { X86_POPFS64, X86_REG_FS, CS_AC_WRITE }, { X86_POPGS64, X86_REG_GS, CS_AC_WRITE }, { X86_POPDS16, X86_REG_DS, CS_AC_WRITE }, { X86_POPES16, X86_REG_ES, CS_AC_WRITE }, { X86_POPFS16, X86_REG_FS, CS_AC_WRITE }, { X86_POPGS16, X86_REG_GS, CS_AC_WRITE }, { X86_POPSS16, X86_REG_SS, CS_AC_WRITE }, #ifndef CAPSTONE_X86_REDUCE { X86_SKINIT, X86_REG_EAX, CS_AC_WRITE }, { X86_VMRUN32, X86_REG_EAX, CS_AC_WRITE }, { X86_VMRUN64, X86_REG_RAX, CS_AC_WRITE }, { X86_VMLOAD32, X86_REG_EAX, CS_AC_WRITE }, { X86_VMLOAD64, X86_REG_RAX, CS_AC_WRITE }, { X86_VMSAVE32, X86_REG_EAX, CS_AC_READ }, { X86_VMSAVE64, X86_REG_RAX, CS_AC_READ }, { X86_FNSTSW16r, X86_REG_AX, CS_AC_WRITE }, { X86_CMOVB_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVBE_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVE_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVP_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVNB_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVNBE_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVNE_F, X86_REG_ST0, CS_AC_WRITE }, { X86_CMOVNP_F, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FXCHST0r, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FXCHST0r_alt, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FCOMST0r, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FCOMPST0r, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FCOMPST0r_alt, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FPST0r, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FPST0r_alt, X86_REG_ST0, CS_AC_WRITE }, { X86_ST_FPNCEST0r, X86_REG_ST0, CS_AC_WRITE }, #endif }; static struct insn_reg2 insn_regs_intel2[] = { { X86_IN8rr, X86_REG_AL, X86_REG_DX, CS_AC_WRITE, CS_AC_READ }, { X86_IN16rr, X86_REG_AX, X86_REG_DX, CS_AC_WRITE, CS_AC_READ }, { X86_IN32rr, X86_REG_EAX, X86_REG_DX, CS_AC_WRITE, CS_AC_READ }, { X86_OUT8rr, X86_REG_DX, X86_REG_AL, CS_AC_READ, CS_AC_READ }, { X86_OUT16rr, X86_REG_DX, X86_REG_AX, CS_AC_READ, CS_AC_READ }, { X86_OUT32rr, X86_REG_DX, X86_REG_EAX, CS_AC_READ, CS_AC_READ }, { X86_INVLPGA32, X86_REG_EAX, X86_REG_ECX, CS_AC_READ, CS_AC_READ }, { X86_INVLPGA64, X86_REG_RAX, X86_REG_ECX, CS_AC_READ, CS_AC_READ }, }; static struct insn_reg insn_regs_intel_sorted [ARR_SIZE(insn_regs_intel)]; static int regs_cmp(const void *a, const void *b) { uint16_t l = ((struct insn_reg *)a)->insn; uint16_t r = ((struct insn_reg *)b)->insn; return (l - r); } // return register of given instruction id // return 0 if not found // this is to handle instructions embedding accumulate registers into AsmStrs[] x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access) { static bool intel_regs_sorted = false; unsigned int first = 0; unsigned int last = ARR_SIZE(insn_regs_intel) - 1; unsigned int mid; if (!intel_regs_sorted) { memcpy(insn_regs_intel_sorted, insn_regs_intel, sizeof(insn_regs_intel_sorted)); qsort(insn_regs_intel_sorted, ARR_SIZE(insn_regs_intel_sorted), sizeof(struct insn_reg), regs_cmp); intel_regs_sorted = true; } if (insn_regs_intel_sorted[0].insn > id || insn_regs_intel_sorted[last].insn < id) { return 0; } while (first <= last) { mid = (first + last) / 2; if (insn_regs_intel_sorted[mid].insn < id) { first = mid + 1; } else if (insn_regs_intel_sorted[mid].insn == id) { if (access) { *access = insn_regs_intel_sorted[mid].access; } return insn_regs_intel_sorted[mid].reg; } else { if (mid == 0) break; last = mid - 1; } } // not found return 0; } bool X86_insn_reg_intel2(unsigned int id, x86_reg *reg1, enum cs_ac_type *access1, x86_reg *reg2, enum cs_ac_type *access2) { unsigned int i; for (i = 0; i < ARR_SIZE(insn_regs_intel2); i++) { if (insn_regs_intel2[i].insn == id) { *reg1 = insn_regs_intel2[i].reg1; *reg2 = insn_regs_intel2[i].reg2; if (access1) *access1 = insn_regs_intel2[i].access1; if (access2) *access2 = insn_regs_intel2[i].access2; return true; } } // not found return false; } // ATT just reuses Intel data, but with the order of registers reversed bool X86_insn_reg_att2(unsigned int id, x86_reg *reg1, enum cs_ac_type *access1, x86_reg *reg2, enum cs_ac_type *access2) { unsigned int i; for (i = 0; i < ARR_SIZE(insn_regs_intel2); i++) { if (insn_regs_intel2[i].insn == id) { // reverse order of Intel syntax registers *reg1 = insn_regs_intel2[i].reg2; *reg2 = insn_regs_intel2[i].reg1; if (access1) *access1 = insn_regs_intel2[i].access2; if (access2) *access2 = insn_regs_intel2[i].access1; return true; } } // not found return false; } x86_reg X86_insn_reg_att(unsigned int id, enum cs_ac_type *access) { unsigned int i; for (i = 0; i < ARR_SIZE(insn_regs_att); i++) { if (insn_regs_att[i].insn == id) { if (access) *access = insn_regs_intel[i].access; return insn_regs_att[i].reg; } } // not found return 0; } // given MCInst's id, find out if this insn is valid for REPNE prefix static bool valid_repne(cs_struct *h, unsigned int opcode) { unsigned int id; int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache); if (i != 0) { id = insns[i].mapid; switch(id) { default: return false; case X86_INS_CMPSB: case X86_INS_CMPSW: case X86_INS_CMPSQ: case X86_INS_SCASB: case X86_INS_SCASW: case X86_INS_SCASQ: case X86_INS_MOVSB: case X86_INS_MOVSW: case X86_INS_MOVSD: case X86_INS_MOVSQ: case X86_INS_LODSB: case X86_INS_LODSW: case X86_INS_LODSD: case X86_INS_LODSQ: case X86_INS_STOSB: case X86_INS_STOSW: case X86_INS_STOSD: case X86_INS_STOSQ: case X86_INS_INSB: case X86_INS_INSW: case X86_INS_INSD: case X86_INS_OUTSB: case X86_INS_OUTSW: case X86_INS_OUTSD: return true; case X86_INS_CMPSD: if (opcode == X86_CMPSL) // REP CMPSD return true; return false; case X86_INS_SCASD: if (opcode == X86_SCASL) // REP SCASD return true; return false; } } // not found return false; } // given MCInst's id, find out if this insn is valid for REP prefix static bool valid_rep(cs_struct *h, unsigned int opcode) { unsigned int id; int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache); if (i != 0) { id = insns[i].mapid; switch(id) { default: return false; case X86_INS_MOVSB: case X86_INS_MOVSW: case X86_INS_MOVSQ: case X86_INS_LODSB: case X86_INS_LODSW: case X86_INS_LODSQ: case X86_INS_STOSB: case X86_INS_STOSW: case X86_INS_STOSQ: case X86_INS_INSB: case X86_INS_INSW: case X86_INS_INSD: case X86_INS_OUTSB: case X86_INS_OUTSW: case X86_INS_OUTSD: return true; // following are some confused instructions, which have the same // mnemonics in 128bit media instructions. Intel is horribly crazy! case X86_INS_MOVSD: if (opcode == X86_MOVSL) // REP MOVSD return true; return false; case X86_INS_LODSD: if (opcode == X86_LODSL) // REP LODSD return true; return false; case X86_INS_STOSD: if (opcode == X86_STOSL) // REP STOSD return true; return false; } } // not found return false; } // given MCInst's id, find out if this insn is valid for REPE prefix static bool valid_repe(cs_struct *h, unsigned int opcode) { unsigned int id; int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache); if (i != 0) { id = insns[i].mapid; switch(id) { default: return false; case X86_INS_CMPSB: case X86_INS_CMPSW: case X86_INS_CMPSQ: case X86_INS_SCASB: case X86_INS_SCASW: case X86_INS_SCASQ: return true; // following are some confused instructions, which have the same // mnemonics in 128bit media instructions. Intel is horribly crazy! case X86_INS_CMPSD: if (opcode == X86_CMPSL) // REP CMPSD return true; return false; case X86_INS_SCASD: if (opcode == X86_SCASL) // REP SCASD return true; return false; } } // not found return false; } #ifndef CAPSTONE_DIET // add *CX register to regs_read[] & regs_write[] static void add_cx(MCInst *MI) { if (MI->csh->detail) { x86_reg cx; if (MI->csh->mode & CS_MODE_16) cx = X86_REG_CX; else if (MI->csh->mode & CS_MODE_32) cx = X86_REG_ECX; else // 64-bit cx = X86_REG_RCX; MI->flat_insn->detail->regs_read[MI->flat_insn->detail->regs_read_count] = cx; MI->flat_insn->detail->regs_read_count++; MI->flat_insn->detail->regs_write[MI->flat_insn->detail->regs_write_count] = cx; MI->flat_insn->detail->regs_write_count++; } } #endif // return true if we patch the mnemonic bool X86_lockrep(MCInst *MI, SStream *O) { unsigned int opcode; bool res = false; switch(MI->x86_prefix[0]) { default: break; case 0xf0: #ifndef CAPSTONE_DIET SStream_concat(O, "lock|"); #endif break; case 0xf2: // repne opcode = MCInst_getOpcode(MI); #ifndef CAPSTONE_DIET // only care about memonic in standard (non-diet) mode if (valid_repne(MI->csh, opcode)) { SStream_concat(O, "repne|"); add_cx(MI); } else { // invalid prefix MI->x86_prefix[0] = 0; // handle special cases #ifndef CAPSTONE_X86_REDUCE if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSDrr); SStream_concat(O, "mulsd\t"); res = true; } #endif } #else // diet mode -> only patch opcode in special cases if (!valid_repne(MI->csh, opcode)) { MI->x86_prefix[0] = 0; } #ifndef CAPSTONE_X86_REDUCE // handle special cases if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSDrr); } #endif #endif break; case 0xf3: opcode = MCInst_getOpcode(MI); #ifndef CAPSTONE_DIET // only care about memonic in standard (non-diet) mode if (valid_rep(MI->csh, opcode)) { SStream_concat(O, "rep|"); add_cx(MI); } else if (valid_repe(MI->csh, opcode)) { SStream_concat(O, "repe|"); add_cx(MI); } else { // invalid prefix MI->x86_prefix[0] = 0; // handle special cases #ifndef CAPSTONE_X86_REDUCE if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSSrr); SStream_concat(O, "mulss\t"); res = true; } #endif } #else // diet mode -> only patch opcode in special cases if (!valid_rep(MI->csh, opcode) && !valid_repe(MI->csh, opcode)) { MI->x86_prefix[0] = 0; } #ifndef CAPSTONE_X86_REDUCE // handle special cases if (opcode == X86_MULPDrr) { MCInst_setOpcode(MI, X86_MULSSrr); } #endif #endif break; } // copy normalized prefix[] back to x86.prefix[] if (MI->csh->detail) memcpy(MI->flat_insn->detail->x86.prefix, MI->x86_prefix, ARR_SIZE(MI->x86_prefix)); return res; } void op_addReg(MCInst *MI, int reg) { if (MI->csh->detail) { MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].type = X86_OP_REG; MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].reg = reg; MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].size = MI->csh->regsize_map[reg]; MI->flat_insn->detail->x86.op_count++; } if (MI->op1_size == 0) MI->op1_size = MI->csh->regsize_map[reg]; } void op_addImm(MCInst *MI, int v) { if (MI->csh->detail) { MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].type = X86_OP_IMM; MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].imm = v; // if op_count > 0, then this operand's size is taken from the destination op if (MI->csh->syntax != CS_OPT_SYNTAX_ATT) { if (MI->flat_insn->detail->x86.op_count > 0) MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].size = MI->flat_insn->detail->x86.operands[0].size; else MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].size = MI->imm_size; } else MI->has_imm = true; MI->flat_insn->detail->x86.op_count++; } if (MI->op1_size == 0) MI->op1_size = MI->imm_size; } void op_addXopCC(MCInst *MI, int v) { if (MI->csh->detail) { MI->flat_insn->detail->x86.xop_cc = v; } } void op_addSseCC(MCInst *MI, int v) { if (MI->csh->detail) { MI->flat_insn->detail->x86.sse_cc = v; } } void op_addAvxCC(MCInst *MI, int v) { if (MI->csh->detail) { MI->flat_insn->detail->x86.avx_cc = v; } } void op_addAvxRoundingMode(MCInst *MI, int v) { if (MI->csh->detail) { MI->flat_insn->detail->x86.avx_rm = v; } } // below functions supply details to X86GenAsmWriter*.inc void op_addAvxZeroOpmask(MCInst *MI) { if (MI->csh->detail) { // link with the previous operand MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count - 1].avx_zero_opmask = true; } } void op_addAvxSae(MCInst *MI) { if (MI->csh->detail) { MI->flat_insn->detail->x86.avx_sae = true; } } void op_addAvxBroadcast(MCInst *MI, x86_avx_bcast v) { if (MI->csh->detail) { // link with the previous operand MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count - 1].avx_bcast = v; } } #ifndef CAPSTONE_DIET // map instruction to its characteristics typedef struct insn_op { uint64_t eflags; // how this instruction update EFLAGS uint8_t access[6]; } insn_op; static insn_op insn_ops[] = { { /* NULL item */ 0, { 0 } }, #ifdef CAPSTONE_X86_REDUCE #include "X86MappingInsnOp_reduce.inc" #else #include "X86MappingInsnOp.inc" #endif }; // given internal insn id, return operand access info uint8_t *X86_get_op_access(cs_struct *h, unsigned int id, uint64_t *eflags) { int i = insn_find(insns, ARR_SIZE(insns), id, &h->insn_cache); if (i != 0) { *eflags = insn_ops[i].eflags; return insn_ops[i].access; } return NULL; } void X86_reg_access(const cs_insn *insn, cs_regs regs_read, uint8_t *regs_read_count, cs_regs regs_write, uint8_t *regs_write_count) { uint8_t i; uint8_t read_count, write_count; cs_x86 *x86 = &(insn->detail->x86); read_count = insn->detail->regs_read_count; write_count = insn->detail->regs_write_count; // implicit registers memcpy(regs_read, insn->detail->regs_read, read_count * sizeof(insn->detail->regs_read[0])); memcpy(regs_write, insn->detail->regs_write, write_count * sizeof(insn->detail->regs_write[0])); // explicit registers for (i = 0; i < x86->op_count; i++) { cs_x86_op *op = &(x86->operands[i]); switch((int)op->type) { case X86_OP_REG: if ((op->access & CS_AC_READ) && !arr_exist(regs_read, read_count, op->reg)) { regs_read[read_count] = op->reg; read_count++; } if ((op->access & CS_AC_WRITE) && !arr_exist(regs_write, write_count, op->reg)) { regs_write[write_count] = op->reg; write_count++; } break; case X86_OP_MEM: // registers appeared in memory references always being read if ((op->mem.segment != X86_REG_INVALID)) { regs_read[read_count] = op->mem.segment; read_count++; } if ((op->mem.base != X86_REG_INVALID) && !arr_exist(regs_read, read_count, op->mem.base)) { regs_read[read_count] = op->mem.base; read_count++; } if ((op->mem.index != X86_REG_INVALID) && !arr_exist(regs_read, read_count, op->mem.index)) { regs_read[read_count] = op->mem.index; read_count++; } default: break; } } *regs_read_count = read_count; *regs_write_count = write_count; } #endif // map immediate size to instruction id static struct size_id { unsigned char size; unsigned short id; } x86_imm_size[] = { #include "X86ImmSize.inc" }; // given the instruction name, return the size of its immediate operand (or 0) int X86_immediate_size(unsigned int id) { #if 0 // linear searching unsigned int i; for (i = 0; i < ARR_SIZE(x86_imm_size); i++) { if (id == x86_imm_size[i].id) { return x86_imm_size[i].size; } } #endif // binary searching since the IDs is sorted in order unsigned int left, right, m; left = 0; right = ARR_SIZE(x86_imm_size) - 1; while(left <= right) { m = (left + right) / 2; if (id == x86_imm_size[m].id) return x86_imm_size[m].size; if (id < x86_imm_size[m].id) right = m - 1; else left = m + 1; } // not found return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_5271_0
crossvul-cpp_data_good_3946_5
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Protocol Security Negotiation * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 Norbert Federa <norbert.federa@thincast.com> * Copyright 2015 Thincast Technologies GmbH * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.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 <winpr/crt.h> #include <freerdp/log.h> #include "tpkt.h" #include "nego.h" #include "transport.h" #define TAG FREERDP_TAG("core.nego") struct rdp_nego { UINT16 port; UINT32 flags; const char* hostname; char* cookie; BYTE* RoutingToken; DWORD RoutingTokenLength; BOOL SendPreconnectionPdu; UINT32 PreconnectionId; char* PreconnectionBlob; NEGO_STATE state; BOOL TcpConnected; BOOL SecurityConnected; UINT32 CookieMaxLength; BOOL sendNegoData; UINT32 SelectedProtocol; UINT32 RequestedProtocols; BOOL NegotiateSecurityLayer; BOOL EnabledProtocols[16]; BOOL RestrictedAdminModeRequired; BOOL GatewayEnabled; BOOL GatewayBypassLocal; rdpTransport* transport; }; static const char* nego_state_string(NEGO_STATE state) { static const char* const NEGO_STATE_STRINGS[] = { "NEGO_STATE_INITIAL", "NEGO_STATE_EXT", "NEGO_STATE_NLA", "NEGO_STATE_TLS", "NEGO_STATE_RDP", "NEGO_STATE_FAIL", "NEGO_STATE_FINAL", "NEGO_STATE_INVALID" }; if (state >= ARRAYSIZE(NEGO_STATE_STRINGS)) return NEGO_STATE_STRINGS[ARRAYSIZE(NEGO_STATE_STRINGS) - 1]; return NEGO_STATE_STRINGS[state]; } static const char* protocol_security_string(UINT32 security) { static const char* PROTOCOL_SECURITY_STRINGS[] = { "RDP", "TLS", "NLA", "UNK", "UNK", "UNK", "UNK", "UNK", "EXT", "UNK" }; if (security >= ARRAYSIZE(PROTOCOL_SECURITY_STRINGS)) return PROTOCOL_SECURITY_STRINGS[ARRAYSIZE(PROTOCOL_SECURITY_STRINGS) - 1]; return PROTOCOL_SECURITY_STRINGS[security]; } static BOOL nego_transport_connect(rdpNego* nego); static BOOL nego_transport_disconnect(rdpNego* nego); static BOOL nego_security_connect(rdpNego* nego); static BOOL nego_send_preconnection_pdu(rdpNego* nego); static BOOL nego_recv_response(rdpNego* nego); static void nego_send(rdpNego* nego); static BOOL nego_process_negotiation_request(rdpNego* nego, wStream* s); static BOOL nego_process_negotiation_response(rdpNego* nego, wStream* s); static BOOL nego_process_negotiation_failure(rdpNego* nego, wStream* s); /** * Negotiate protocol security and connect. * @param nego * @return */ BOOL nego_connect(rdpNego* nego) { rdpSettings* settings = nego->transport->settings; if (nego->state == NEGO_STATE_INITIAL) { if (nego->EnabledProtocols[PROTOCOL_HYBRID_EX]) { nego->state = NEGO_STATE_EXT; } else if (nego->EnabledProtocols[PROTOCOL_HYBRID]) { nego->state = NEGO_STATE_NLA; } else if (nego->EnabledProtocols[PROTOCOL_SSL]) { nego->state = NEGO_STATE_TLS; } else if (nego->EnabledProtocols[PROTOCOL_RDP]) { nego->state = NEGO_STATE_RDP; } else { WLog_ERR(TAG, "No security protocol is enabled"); nego->state = NEGO_STATE_FAIL; return FALSE; } if (!nego->NegotiateSecurityLayer) { WLog_DBG(TAG, "Security Layer Negotiation is disabled"); /* attempt only the highest enabled protocol (see nego_attempt_*) */ nego->EnabledProtocols[PROTOCOL_HYBRID] = FALSE; nego->EnabledProtocols[PROTOCOL_SSL] = FALSE; nego->EnabledProtocols[PROTOCOL_RDP] = FALSE; nego->EnabledProtocols[PROTOCOL_HYBRID_EX] = FALSE; if (nego->state == NEGO_STATE_EXT) { nego->EnabledProtocols[PROTOCOL_HYBRID_EX] = TRUE; nego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE; nego->SelectedProtocol = PROTOCOL_HYBRID_EX; } else if (nego->state == NEGO_STATE_NLA) { nego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE; nego->SelectedProtocol = PROTOCOL_HYBRID; } else if (nego->state == NEGO_STATE_TLS) { nego->EnabledProtocols[PROTOCOL_SSL] = TRUE; nego->SelectedProtocol = PROTOCOL_SSL; } else if (nego->state == NEGO_STATE_RDP) { nego->EnabledProtocols[PROTOCOL_RDP] = TRUE; nego->SelectedProtocol = PROTOCOL_RDP; } } if (nego->SendPreconnectionPdu) { if (!nego_send_preconnection_pdu(nego)) { WLog_ERR(TAG, "Failed to send preconnection pdu"); nego->state = NEGO_STATE_FINAL; return FALSE; } } } if (!nego->NegotiateSecurityLayer) { nego->state = NEGO_STATE_FINAL; } else { do { WLog_DBG(TAG, "state: %s", nego_state_string(nego->state)); nego_send(nego); if (nego->state == NEGO_STATE_FAIL) { if (freerdp_get_last_error(nego->transport->context) == FREERDP_ERROR_SUCCESS) WLog_ERR(TAG, "Protocol Security Negotiation Failure"); nego->state = NEGO_STATE_FINAL; return FALSE; } } while (nego->state != NEGO_STATE_FINAL); } WLog_DBG(TAG, "Negotiated %s security", protocol_security_string(nego->SelectedProtocol)); /* update settings with negotiated protocol security */ settings->RequestedProtocols = nego->RequestedProtocols; settings->SelectedProtocol = nego->SelectedProtocol; settings->NegotiationFlags = nego->flags; if (nego->SelectedProtocol == PROTOCOL_RDP) { settings->UseRdpSecurityLayer = TRUE; if (!settings->EncryptionMethods) { /** * Advertise all supported encryption methods if the client * implementation did not set any security methods */ settings->EncryptionMethods = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_56BIT | ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS; } } /* finally connect security layer (if not already done) */ if (!nego_security_connect(nego)) { WLog_DBG(TAG, "Failed to connect with %s security", protocol_security_string(nego->SelectedProtocol)); return FALSE; } return TRUE; } BOOL nego_disconnect(rdpNego* nego) { nego->state = NEGO_STATE_INITIAL; return nego_transport_disconnect(nego); } /* connect to selected security layer */ BOOL nego_security_connect(rdpNego* nego) { if (!nego->TcpConnected) { nego->SecurityConnected = FALSE; } else if (!nego->SecurityConnected) { if (nego->SelectedProtocol == PROTOCOL_HYBRID) { WLog_DBG(TAG, "nego_security_connect with PROTOCOL_HYBRID"); nego->SecurityConnected = transport_connect_nla(nego->transport); } else if (nego->SelectedProtocol == PROTOCOL_SSL) { WLog_DBG(TAG, "nego_security_connect with PROTOCOL_SSL"); nego->SecurityConnected = transport_connect_tls(nego->transport); } else if (nego->SelectedProtocol == PROTOCOL_RDP) { WLog_DBG(TAG, "nego_security_connect with PROTOCOL_RDP"); nego->SecurityConnected = transport_connect_rdp(nego->transport); } else { WLog_ERR(TAG, "cannot connect security layer because no protocol has been selected yet."); } } return nego->SecurityConnected; } /** * Connect TCP layer. * @param nego * @return */ static BOOL nego_tcp_connect(rdpNego* nego) { if (!nego->TcpConnected) { if (nego->GatewayEnabled) { if (nego->GatewayBypassLocal) { /* Attempt a direct connection first, and then fallback to using the gateway */ WLog_INFO(TAG, "Detecting if host can be reached locally. - This might take some time."); WLog_INFO(TAG, "To disable auto detection use /gateway-usage-method:direct"); transport_set_gateway_enabled(nego->transport, FALSE); nego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 1); } if (!nego->TcpConnected) { transport_set_gateway_enabled(nego->transport, TRUE); nego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 15); } } else { nego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 15); } } return nego->TcpConnected; } /** * Connect TCP layer. For direct approach, connect security layer as well. * @param nego * @return */ BOOL nego_transport_connect(rdpNego* nego) { if (!nego_tcp_connect(nego)) return FALSE; if (nego->TcpConnected && !nego->NegotiateSecurityLayer) return nego_security_connect(nego); return nego->TcpConnected; } /** * Disconnect TCP layer. * @param nego * @return */ BOOL nego_transport_disconnect(rdpNego* nego) { if (nego->TcpConnected) transport_disconnect(nego->transport); nego->TcpConnected = FALSE; nego->SecurityConnected = FALSE; return TRUE; } /** * Send preconnection information if enabled. * @param nego * @return */ BOOL nego_send_preconnection_pdu(rdpNego* nego) { wStream* s; UINT32 cbSize; UINT16 cchPCB = 0; WCHAR* wszPCB = NULL; WLog_DBG(TAG, "Sending preconnection PDU"); if (!nego_tcp_connect(nego)) return FALSE; /* it's easier to always send the version 2 PDU, and it's just 2 bytes overhead */ cbSize = PRECONNECTION_PDU_V2_MIN_SIZE; if (nego->PreconnectionBlob) { cchPCB = (UINT16)ConvertToUnicode(CP_UTF8, 0, nego->PreconnectionBlob, -1, &wszPCB, 0); cchPCB += 1; /* zero-termination */ cbSize += cchPCB * 2; } s = Stream_New(NULL, cbSize); if (!s) { free(wszPCB); WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } Stream_Write_UINT32(s, cbSize); /* cbSize */ Stream_Write_UINT32(s, 0); /* Flags */ Stream_Write_UINT32(s, PRECONNECTION_PDU_V2); /* Version */ Stream_Write_UINT32(s, nego->PreconnectionId); /* Id */ Stream_Write_UINT16(s, cchPCB); /* cchPCB */ if (wszPCB) { Stream_Write(s, wszPCB, cchPCB * 2); /* wszPCB */ free(wszPCB); } Stream_SealLength(s); if (transport_write(nego->transport, s) < 0) { Stream_Free(s, TRUE); return FALSE; } Stream_Free(s, TRUE); return TRUE; } /** * Attempt negotiating NLA + TLS extended security. * @param nego */ static void nego_attempt_ext(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL | PROTOCOL_HYBRID_EX; WLog_DBG(TAG, "Attempting NLA extended security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } WLog_DBG(TAG, "state: %s", nego_state_string(nego->state)); if (nego->state != NEGO_STATE_FINAL) { nego_transport_disconnect(nego); if (nego->EnabledProtocols[PROTOCOL_HYBRID]) nego->state = NEGO_STATE_NLA; else if (nego->EnabledProtocols[PROTOCOL_SSL]) nego->state = NEGO_STATE_TLS; else if (nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_RDP; else nego->state = NEGO_STATE_FAIL; } } /** * Attempt negotiating NLA + TLS security. * @param nego */ static void nego_attempt_nla(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL; WLog_DBG(TAG, "Attempting NLA security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } WLog_DBG(TAG, "state: %s", nego_state_string(nego->state)); if (nego->state != NEGO_STATE_FINAL) { nego_transport_disconnect(nego); if (nego->EnabledProtocols[PROTOCOL_SSL]) nego->state = NEGO_STATE_TLS; else if (nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_RDP; else nego->state = NEGO_STATE_FAIL; } } /** * Attempt negotiating TLS security. * @param nego */ static void nego_attempt_tls(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_SSL; WLog_DBG(TAG, "Attempting TLS security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (nego->state != NEGO_STATE_FINAL) { nego_transport_disconnect(nego); if (nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_RDP; else nego->state = NEGO_STATE_FAIL; } } /** * Attempt negotiating standard RDP security. * @param nego */ static void nego_attempt_rdp(rdpNego* nego) { nego->RequestedProtocols = PROTOCOL_RDP; WLog_DBG(TAG, "Attempting RDP security"); if (!nego_transport_connect(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_send_negotiation_request(nego)) { nego->state = NEGO_STATE_FAIL; return; } if (!nego_recv_response(nego)) { nego->state = NEGO_STATE_FAIL; return; } } /** * Wait to receive a negotiation response * @param nego */ BOOL nego_recv_response(rdpNego* nego) { int status; wStream* s; s = Stream_New(NULL, 1024); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } status = transport_read_pdu(nego->transport, s); if (status < 0) { Stream_Free(s, TRUE); return FALSE; } status = nego_recv(nego->transport, s, nego); Stream_Free(s, TRUE); if (status < 0) return FALSE; return TRUE; } /** * Receive protocol security negotiation message.\n * @msdn{cc240501} * @param transport transport * @param s stream * @param extra nego pointer */ int nego_recv(rdpTransport* transport, wStream* s, void* extra) { BYTE li; BYTE type; UINT16 length; rdpNego* nego = (rdpNego*)extra; if (!tpkt_read_header(s, &length)) return -1; if (!tpdu_read_connection_confirm(s, &li, length)) return -1; if (li > 6) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ switch (type) { case TYPE_RDP_NEG_RSP: if (!nego_process_negotiation_response(nego, s)) return -1; WLog_DBG(TAG, "selected_protocol: %" PRIu32 "", nego->SelectedProtocol); /* enhanced security selected ? */ if (nego->SelectedProtocol) { if ((nego->SelectedProtocol == PROTOCOL_HYBRID) && (!nego->EnabledProtocols[PROTOCOL_HYBRID])) { nego->state = NEGO_STATE_FAIL; } if ((nego->SelectedProtocol == PROTOCOL_SSL) && (!nego->EnabledProtocols[PROTOCOL_SSL])) { nego->state = NEGO_STATE_FAIL; } } else if (!nego->EnabledProtocols[PROTOCOL_RDP]) { nego->state = NEGO_STATE_FAIL; } break; case TYPE_RDP_NEG_FAILURE: if (!nego_process_negotiation_failure(nego, s)) return -1; break; } } else if (li == 6) { WLog_DBG(TAG, "no rdpNegData"); if (!nego->EnabledProtocols[PROTOCOL_RDP]) nego->state = NEGO_STATE_FAIL; else nego->state = NEGO_STATE_FINAL; } else { WLog_ERR(TAG, "invalid negotiation response"); nego->state = NEGO_STATE_FAIL; } if (!tpkt_ensure_stream_consumed(s, length)) return -1; return 0; } /** * Read optional routing token or cookie of X.224 Connection Request PDU. * @msdn{cc240470} * @param nego * @param s stream */ static BOOL nego_read_request_token_or_cookie(rdpNego* nego, wStream* s) { /* routingToken and cookie are optional and mutually exclusive! * * routingToken (variable): An optional and variable-length routing * token (used for load balancing) terminated by a 0x0D0A two-byte * sequence: (check [MSFT-SDLBTS] for details!) * Cookie:[space]msts=[ip address].[port].[reserved][\x0D\x0A] * * cookie (variable): An optional and variable-length ANSI character * string terminated by a 0x0D0A two-byte sequence: * Cookie:[space]mstshash=[ANSISTRING][\x0D\x0A] */ BYTE* str = NULL; UINT16 crlf = 0; size_t pos, len; BOOL result = FALSE; BOOL isToken = FALSE; size_t remain = Stream_GetRemainingLength(s); str = Stream_Pointer(s); pos = Stream_GetPosition(s); /* minimum length for token is 15 */ if (remain < 15) return TRUE; if (memcmp(Stream_Pointer(s), "Cookie: mstshash=", 17) != 0) { isToken = TRUE; } else { /* not a token, minimum length for cookie is 19 */ if (remain < 19) return TRUE; Stream_Seek(s, 17); } while ((remain = Stream_GetRemainingLength(s)) >= 2) { Stream_Read_UINT16(s, crlf); if (crlf == 0x0A0D) break; Stream_Rewind(s, 1); } if (crlf == 0x0A0D) { Stream_Rewind(s, 2); len = Stream_GetPosition(s) - pos; remain = Stream_GetRemainingLength(s); Stream_Write_UINT16(s, 0); if (strnlen((char*)str, len) == len) { if (isToken) result = nego_set_routing_token(nego, str, len); else result = nego_set_cookie(nego, (char*)str); } } if (!result) { Stream_SetPosition(s, pos); WLog_ERR(TAG, "invalid %s received", isToken ? "routing token" : "cookie"); } else { WLog_DBG(TAG, "received %s [%s]", isToken ? "routing token" : "cookie", str); } return result; } /** * Read protocol security negotiation request message.\n * @param nego * @param s stream */ BOOL nego_read_request(rdpNego* nego, wStream* s) { BYTE li; BYTE type; UINT16 length; if (!tpkt_read_header(s, &length)) return FALSE; if (!tpdu_read_connection_request(s, &li, length)) return FALSE; if (li != Stream_GetRemainingLength(s) + 6) { WLog_ERR(TAG, "Incorrect TPDU length indicator."); return FALSE; } if (!nego_read_request_token_or_cookie(nego, s)) { WLog_ERR(TAG, "Failed to parse routing token or cookie."); return FALSE; } if (Stream_GetRemainingLength(s) >= 8) { /* rdpNegData (optional) */ Stream_Read_UINT8(s, type); /* Type */ if (type != TYPE_RDP_NEG_REQ) { WLog_ERR(TAG, "Incorrect negotiation request type %" PRIu8 "", type); return FALSE; } if (!nego_process_negotiation_request(nego, s)) return FALSE; } return tpkt_ensure_stream_consumed(s, length); } /** * Send protocol security negotiation message. * @param nego */ void nego_send(rdpNego* nego) { if (nego->state == NEGO_STATE_EXT) nego_attempt_ext(nego); else if (nego->state == NEGO_STATE_NLA) nego_attempt_nla(nego); else if (nego->state == NEGO_STATE_TLS) nego_attempt_tls(nego); else if (nego->state == NEGO_STATE_RDP) nego_attempt_rdp(nego); else WLog_ERR(TAG, "invalid negotiation state for sending"); } /** * Send RDP Negotiation Request (RDP_NEG_REQ).\n * @msdn{cc240500}\n * @msdn{cc240470} * @param nego */ BOOL nego_send_negotiation_request(rdpNego* nego) { BOOL rc = FALSE; wStream* s; size_t length; size_t bm, em; BYTE flags = 0; size_t cookie_length; s = Stream_New(NULL, 512); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } length = TPDU_CONNECTION_REQUEST_LENGTH; bm = Stream_GetPosition(s); Stream_Seek(s, length); if (nego->RoutingToken) { Stream_Write(s, nego->RoutingToken, nego->RoutingTokenLength); /* Ensure Routing Token is correctly terminated - may already be present in string */ if ((nego->RoutingTokenLength > 2) && (nego->RoutingToken[nego->RoutingTokenLength - 2] == 0x0D) && (nego->RoutingToken[nego->RoutingTokenLength - 1] == 0x0A)) { WLog_DBG(TAG, "Routing token looks correctly terminated - use verbatim"); length += nego->RoutingTokenLength; } else { WLog_DBG(TAG, "Adding terminating CRLF to routing token"); Stream_Write_UINT8(s, 0x0D); /* CR */ Stream_Write_UINT8(s, 0x0A); /* LF */ length += nego->RoutingTokenLength + 2; } } else if (nego->cookie) { cookie_length = strlen(nego->cookie); if (cookie_length > nego->CookieMaxLength) cookie_length = nego->CookieMaxLength; Stream_Write(s, "Cookie: mstshash=", 17); Stream_Write(s, (BYTE*)nego->cookie, cookie_length); Stream_Write_UINT8(s, 0x0D); /* CR */ Stream_Write_UINT8(s, 0x0A); /* LF */ length += cookie_length + 19; } WLog_DBG(TAG, "RequestedProtocols: %" PRIu32 "", nego->RequestedProtocols); if ((nego->RequestedProtocols > PROTOCOL_RDP) || (nego->sendNegoData)) { /* RDP_NEG_DATA must be present for TLS and NLA */ if (nego->RestrictedAdminModeRequired) flags |= RESTRICTED_ADMIN_MODE_REQUIRED; Stream_Write_UINT8(s, TYPE_RDP_NEG_REQ); Stream_Write_UINT8(s, flags); Stream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */ Stream_Write_UINT32(s, nego->RequestedProtocols); /* requestedProtocols */ length += 8; } if (length > UINT16_MAX) goto fail; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); tpkt_write_header(s, (UINT16)length); tpdu_write_connection_request(s, (UINT16)length - 5); Stream_SetPosition(s, em); Stream_SealLength(s); rc = (transport_write(nego->transport, s) >= 0); fail: Stream_Free(s, TRUE); return rc; } /** * Process Negotiation Request from Connection Request message. * @param nego * @param s */ BOOL nego_process_negotiation_request(rdpNego* nego, wStream* s) { BYTE flags; UINT16 length; if (Stream_GetRemainingLength(s) < 7) return FALSE; Stream_Read_UINT8(s, flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, nego->RequestedProtocols); WLog_DBG(TAG, "RDP_NEG_REQ: RequestedProtocol: 0x%08" PRIX32 "", nego->RequestedProtocols); nego->state = NEGO_STATE_FINAL; return TRUE; } /** * Process Negotiation Response from Connection Confirm message. * @param nego * @param s */ BOOL nego_process_negotiation_response(rdpNego* nego, wStream* s) { UINT16 length; WLog_DBG(TAG, "RDP_NEG_RSP"); if (Stream_GetRemainingLength(s) < 7) { WLog_ERR(TAG, "Invalid RDP_NEG_RSP"); nego->state = NEGO_STATE_FAIL; return FALSE; } Stream_Read_UINT8(s, nego->flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, nego->SelectedProtocol); nego->state = NEGO_STATE_FINAL; return TRUE; } /** * Process Negotiation Failure from Connection Confirm message. * @param nego * @param s */ BOOL nego_process_negotiation_failure(rdpNego* nego, wStream* s) { BYTE flags; UINT16 length; UINT32 failureCode; WLog_DBG(TAG, "RDP_NEG_FAILURE"); if (Stream_GetRemainingLength(s) < 7) return FALSE; Stream_Read_UINT8(s, flags); Stream_Read_UINT16(s, length); Stream_Read_UINT32(s, failureCode); switch (failureCode) { case SSL_REQUIRED_BY_SERVER: WLog_WARN(TAG, "Error: SSL_REQUIRED_BY_SERVER"); break; case SSL_NOT_ALLOWED_BY_SERVER: WLog_WARN(TAG, "Error: SSL_NOT_ALLOWED_BY_SERVER"); nego->sendNegoData = TRUE; break; case SSL_CERT_NOT_ON_SERVER: WLog_ERR(TAG, "Error: SSL_CERT_NOT_ON_SERVER"); nego->sendNegoData = TRUE; break; case INCONSISTENT_FLAGS: WLog_ERR(TAG, "Error: INCONSISTENT_FLAGS"); break; case HYBRID_REQUIRED_BY_SERVER: WLog_WARN(TAG, "Error: HYBRID_REQUIRED_BY_SERVER"); break; default: WLog_ERR(TAG, "Error: Unknown protocol security error %" PRIu32 "", failureCode); break; } nego->state = NEGO_STATE_FAIL; return TRUE; } /** * Send RDP Negotiation Response (RDP_NEG_RSP).\n * @param nego */ BOOL nego_send_negotiation_response(rdpNego* nego) { UINT16 length; size_t bm, em; BOOL status; wStream* s; BYTE flags; rdpSettings* settings; status = TRUE; settings = nego->transport->settings; s = Stream_New(NULL, 512); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return FALSE; } length = TPDU_CONNECTION_CONFIRM_LENGTH; bm = Stream_GetPosition(s); Stream_Seek(s, length); if (nego->SelectedProtocol & PROTOCOL_FAILED_NEGO) { UINT32 errorCode = (nego->SelectedProtocol & ~PROTOCOL_FAILED_NEGO); flags = 0; Stream_Write_UINT8(s, TYPE_RDP_NEG_FAILURE); Stream_Write_UINT8(s, flags); /* flags */ Stream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */ Stream_Write_UINT32(s, errorCode); length += 8; status = FALSE; } else { flags = EXTENDED_CLIENT_DATA_SUPPORTED; if (settings->SupportGraphicsPipeline) flags |= DYNVC_GFX_PROTOCOL_SUPPORTED; /* RDP_NEG_DATA must be present for TLS, NLA, and RDP */ Stream_Write_UINT8(s, TYPE_RDP_NEG_RSP); Stream_Write_UINT8(s, flags); /* flags */ Stream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */ Stream_Write_UINT32(s, nego->SelectedProtocol); /* selectedProtocol */ length += 8; } em = Stream_GetPosition(s); Stream_SetPosition(s, bm); tpkt_write_header(s, length); tpdu_write_connection_confirm(s, length - 5); Stream_SetPosition(s, em); Stream_SealLength(s); if (transport_write(nego->transport, s) < 0) { Stream_Free(s, TRUE); return FALSE; } Stream_Free(s, TRUE); if (status) { /* update settings with negotiated protocol security */ settings->RequestedProtocols = nego->RequestedProtocols; settings->SelectedProtocol = nego->SelectedProtocol; if (settings->SelectedProtocol == PROTOCOL_RDP) { settings->TlsSecurity = FALSE; settings->NlaSecurity = FALSE; settings->RdpSecurity = TRUE; settings->UseRdpSecurityLayer = TRUE; if (settings->EncryptionLevel == ENCRYPTION_LEVEL_NONE) { /** * If the server implementation did not explicitely set a * encryption level we default to client compatible */ settings->EncryptionLevel = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE; } if (settings->LocalConnection) { /** * Note: This hack was firstly introduced in commit 95f5e115 to * disable the unnecessary encryption with peers connecting to * 127.0.0.1 or local unix sockets. * This also affects connections via port tunnels! (e.g. ssh -L) */ WLog_INFO(TAG, "Turning off encryption for local peer with standard rdp security"); settings->UseRdpSecurityLayer = FALSE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; } if (!settings->RdpServerRsaKey && !settings->RdpKeyFile && !settings->RdpKeyContent) { WLog_ERR(TAG, "Missing server certificate"); return FALSE; } } else if (settings->SelectedProtocol == PROTOCOL_SSL) { settings->TlsSecurity = TRUE; settings->NlaSecurity = FALSE; settings->RdpSecurity = FALSE; settings->UseRdpSecurityLayer = FALSE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; } else if (settings->SelectedProtocol == PROTOCOL_HYBRID) { settings->TlsSecurity = TRUE; settings->NlaSecurity = TRUE; settings->RdpSecurity = FALSE; settings->UseRdpSecurityLayer = FALSE; settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE; } } return status; } /** * Initialize NEGO state machine. * @param nego */ void nego_init(rdpNego* nego) { nego->state = NEGO_STATE_INITIAL; nego->RequestedProtocols = PROTOCOL_RDP; nego->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH; nego->sendNegoData = FALSE; nego->flags = 0; } /** * Create a new NEGO state machine instance. * @param transport * @return */ rdpNego* nego_new(rdpTransport* transport) { rdpNego* nego = (rdpNego*)calloc(1, sizeof(rdpNego)); if (!nego) return NULL; nego->transport = transport; nego_init(nego); return nego; } /** * Free NEGO state machine. * @param nego */ void nego_free(rdpNego* nego) { if (nego) { free(nego->RoutingToken); free(nego->cookie); free(nego); } } /** * Set target hostname and port. * @param nego * @param hostname * @param port */ BOOL nego_set_target(rdpNego* nego, const char* hostname, UINT16 port) { if (!nego || !hostname) return FALSE; nego->hostname = hostname; nego->port = port; return TRUE; } /** * Enable security layer negotiation. * @param nego pointer to the negotiation structure * @param enable_rdp whether to enable security layer negotiation (TRUE for enabled, FALSE for * disabled) */ void nego_set_negotiation_enabled(rdpNego* nego, BOOL NegotiateSecurityLayer) { WLog_DBG(TAG, "Enabling security layer negotiation: %s", NegotiateSecurityLayer ? "TRUE" : "FALSE"); nego->NegotiateSecurityLayer = NegotiateSecurityLayer; } /** * Enable restricted admin mode. * @param nego pointer to the negotiation structure * @param enable_restricted whether to enable security layer negotiation (TRUE for enabled, FALSE * for disabled) */ void nego_set_restricted_admin_mode_required(rdpNego* nego, BOOL RestrictedAdminModeRequired) { WLog_DBG(TAG, "Enabling restricted admin mode: %s", RestrictedAdminModeRequired ? "TRUE" : "FALSE"); nego->RestrictedAdminModeRequired = RestrictedAdminModeRequired; } void nego_set_gateway_enabled(rdpNego* nego, BOOL GatewayEnabled) { nego->GatewayEnabled = GatewayEnabled; } void nego_set_gateway_bypass_local(rdpNego* nego, BOOL GatewayBypassLocal) { nego->GatewayBypassLocal = GatewayBypassLocal; } /** * Enable RDP security protocol. * @param nego pointer to the negotiation structure * @param enable_rdp whether to enable normal RDP protocol (TRUE for enabled, FALSE for disabled) */ void nego_enable_rdp(rdpNego* nego, BOOL enable_rdp) { WLog_DBG(TAG, "Enabling RDP security: %s", enable_rdp ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_RDP] = enable_rdp; } /** * Enable TLS security protocol. * @param nego pointer to the negotiation structure * @param enable_tls whether to enable TLS + RDP protocol (TRUE for enabled, FALSE for disabled) */ void nego_enable_tls(rdpNego* nego, BOOL enable_tls) { WLog_DBG(TAG, "Enabling TLS security: %s", enable_tls ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_SSL] = enable_tls; } /** * Enable NLA security protocol. * @param nego pointer to the negotiation structure * @param enable_nla whether to enable network level authentication protocol (TRUE for enabled, * FALSE for disabled) */ void nego_enable_nla(rdpNego* nego, BOOL enable_nla) { WLog_DBG(TAG, "Enabling NLA security: %s", enable_nla ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_HYBRID] = enable_nla; } /** * Enable NLA extended security protocol. * @param nego pointer to the negotiation structure * @param enable_ext whether to enable network level authentication extended protocol (TRUE for * enabled, FALSE for disabled) */ void nego_enable_ext(rdpNego* nego, BOOL enable_ext) { WLog_DBG(TAG, "Enabling NLA extended security: %s", enable_ext ? "TRUE" : "FALSE"); nego->EnabledProtocols[PROTOCOL_HYBRID_EX] = enable_ext; } /** * Set routing token. * @param nego * @param RoutingToken * @param RoutingTokenLength */ BOOL nego_set_routing_token(rdpNego* nego, BYTE* RoutingToken, DWORD RoutingTokenLength) { if (RoutingTokenLength == 0) return FALSE; free(nego->RoutingToken); nego->RoutingTokenLength = RoutingTokenLength; nego->RoutingToken = (BYTE*)malloc(nego->RoutingTokenLength); if (!nego->RoutingToken) return FALSE; CopyMemory(nego->RoutingToken, RoutingToken, nego->RoutingTokenLength); return TRUE; } /** * Set cookie. * @param nego * @param cookie */ BOOL nego_set_cookie(rdpNego* nego, char* cookie) { if (nego->cookie) { free(nego->cookie); nego->cookie = NULL; } if (!cookie) return TRUE; nego->cookie = _strdup(cookie); if (!nego->cookie) return FALSE; return TRUE; } /** * Set cookie maximum length * @param nego * @param CookieMaxLength */ void nego_set_cookie_max_length(rdpNego* nego, UINT32 CookieMaxLength) { nego->CookieMaxLength = CookieMaxLength; } /** * Enable / disable preconnection PDU. * @param nego * @param send_pcpdu */ void nego_set_send_preconnection_pdu(rdpNego* nego, BOOL SendPreconnectionPdu) { nego->SendPreconnectionPdu = SendPreconnectionPdu; } /** * Set preconnection id. * @param nego * @param id */ void nego_set_preconnection_id(rdpNego* nego, UINT32 PreconnectionId) { nego->PreconnectionId = PreconnectionId; } /** * Set preconnection blob. * @param nego * @param blob */ void nego_set_preconnection_blob(rdpNego* nego, char* PreconnectionBlob) { nego->PreconnectionBlob = PreconnectionBlob; } UINT32 nego_get_selected_protocol(rdpNego* nego) { if (!nego) return 0; return nego->SelectedProtocol; } BOOL nego_set_selected_protocol(rdpNego* nego, UINT32 SelectedProtocol) { if (!nego) return FALSE; nego->SelectedProtocol = SelectedProtocol; return TRUE; } UINT32 nego_get_requested_protocols(rdpNego* nego) { if (!nego) return 0; return nego->RequestedProtocols; } BOOL nego_set_requested_protocols(rdpNego* nego, UINT32 RequestedProtocols) { if (!nego) return FALSE; nego->RequestedProtocols = RequestedProtocols; return TRUE; } NEGO_STATE nego_get_state(rdpNego* nego) { if (!nego) return NEGO_STATE_FAIL; return nego->state; } BOOL nego_set_state(rdpNego* nego, NEGO_STATE state) { if (!nego) return FALSE; nego->state = state; return TRUE; } SEC_WINNT_AUTH_IDENTITY* nego_get_identity(rdpNego* nego) { if (!nego) return NULL; return nla_get_identity(nego->transport->nla); } void nego_free_nla(rdpNego* nego) { if (!nego || !nego->transport) return; nla_free(nego->transport->nla); nego->transport->nla = NULL; } const BYTE* nego_get_routing_token(rdpNego* nego, DWORD* RoutingTokenLength) { if (!nego) return NULL; if (RoutingTokenLength) *RoutingTokenLength = nego->RoutingTokenLength; return nego->RoutingToken; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3946_5
crossvul-cpp_data_bad_4827_0
//--------------------------------------------------------------------------------- // // Little Color Management System // Copyright (c) 1998-2016 Marti Maria Saguer // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //--------------------------------------------------------------------------------- // #include "lcms2_internal.h" // Tag Serialization ----------------------------------------------------------------------------- // This file implements every single tag and tag type as described in the ICC spec. Some types // have been deprecated, like ncl and Data. There is no implementation for those types as there // are no profiles holding them. The programmer can also extend this list by defining his own types // by using the appropriate plug-in. There are three types of plug ins regarding that. First type // allows to define new tags using any existing type. Next plug-in type allows to define new types // and the third one is very specific: allows to extend the number of elements in the multiprocessing // elements special type. //-------------------------------------------------------------------------------------------------- // Some broken types #define cmsCorbisBrokenXYZtype ((cmsTagTypeSignature) 0x17A505B8) #define cmsMonacoBrokenCurveType ((cmsTagTypeSignature) 0x9478ee00) // This is the linked list that keeps track of the defined types typedef struct _cmsTagTypeLinkedList_st { cmsTagTypeHandler Handler; struct _cmsTagTypeLinkedList_st* Next; } _cmsTagTypeLinkedList; // Some macros to define callbacks. #define READ_FN(x) Type_##x##_Read #define WRITE_FN(x) Type_##x##_Write #define FREE_FN(x) Type_##x##_Free #define DUP_FN(x) Type_##x##_Dup // Helper macro to define a handler. Callbacks do have a fixed naming convention. #define TYPE_HANDLER(t, x) { (t), READ_FN(x), WRITE_FN(x), DUP_FN(x), FREE_FN(x), NULL, 0 } // Helper macro to define a MPE handler. Callbacks do have a fixed naming convention #define TYPE_MPE_HANDLER(t, x) { (t), READ_FN(x), WRITE_FN(x), GenericMPEdup, GenericMPEfree, NULL, 0 } // Register a new type handler. This routine is shared between normal types and MPE. LinkedList points to the optional list head static cmsBool RegisterTypesPlugin(cmsContext id, cmsPluginBase* Data, _cmsMemoryClient pos) { cmsPluginTagType* Plugin = (cmsPluginTagType*) Data; _cmsTagTypePluginChunkType* ctx = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(id, pos); _cmsTagTypeLinkedList *pt; // Calling the function with NULL as plug-in would unregister the plug in. if (Data == NULL) { // There is no need to set free the memory, as pool is destroyed as a whole. ctx ->TagTypes = NULL; return TRUE; } // Registering happens in plug-in memory pool. pt = (_cmsTagTypeLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagTypeLinkedList)); if (pt == NULL) return FALSE; pt ->Handler = Plugin ->Handler; pt ->Next = ctx ->TagTypes; ctx ->TagTypes = pt; return TRUE; } // Return handler for a given type or NULL if not found. Shared between normal types and MPE. It first tries the additons // made by plug-ins and then the built-in defaults. static cmsTagTypeHandler* GetHandler(cmsTagTypeSignature sig, _cmsTagTypeLinkedList* PluginLinkedList, _cmsTagTypeLinkedList* DefaultLinkedList) { _cmsTagTypeLinkedList* pt; for (pt = PluginLinkedList; pt != NULL; pt = pt ->Next) { if (sig == pt -> Handler.Signature) return &pt ->Handler; } for (pt = DefaultLinkedList; pt != NULL; pt = pt ->Next) { if (sig == pt -> Handler.Signature) return &pt ->Handler; } return NULL; } // Auxiliary to convert UTF-32 to UTF-16 in some cases static cmsBool _cmsWriteWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, const wchar_t* Array) { cmsUInt32Number i; _cmsAssert(io != NULL); _cmsAssert(!(Array == NULL && n > 0)); for (i=0; i < n; i++) { if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Array[i])) return FALSE; } return TRUE; } // Auxiliary to read an array of wchar_t static cmsBool _cmsReadWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, wchar_t* Array) { cmsUInt32Number i; cmsUInt16Number tmp; _cmsAssert(io != NULL); for (i=0; i < n; i++) { if (Array != NULL) { if (!_cmsReadUInt16Number(io, &tmp)) return FALSE; Array[i] = (wchar_t) tmp; } else { if (!_cmsReadUInt16Number(io, NULL)) return FALSE; } } return TRUE; } // To deal with position tables typedef cmsBool (* PositionTableEntryFn)(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Cargo, cmsUInt32Number n, cmsUInt32Number SizeOfTag); // Helper function to deal with position tables as described in ICC spec 4.3 // A table of n elements is readed, where first comes n records containing offsets and sizes and // then a block containing the data itself. This allows to reuse same data in more than one entry static cmsBool ReadPositionTable(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Count, cmsUInt32Number BaseOffset, void *Cargo, PositionTableEntryFn ElementFn) { cmsUInt32Number i; cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL; // Let's take the offsets to each element ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number)); if (ElementOffsets == NULL) goto Error; ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number)); if (ElementSizes == NULL) goto Error; for (i=0; i < Count; i++) { if (!_cmsReadUInt32Number(io, &ElementOffsets[i])) goto Error; if (!_cmsReadUInt32Number(io, &ElementSizes[i])) goto Error; ElementOffsets[i] += BaseOffset; } // Seek to each element and read it for (i=0; i < Count; i++) { if (!io -> Seek(io, ElementOffsets[i])) goto Error; // This is the reader callback if (!ElementFn(self, io, Cargo, i, ElementSizes[i])) goto Error; } // Success if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets); if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes); return TRUE; Error: if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets); if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes); return FALSE; } // Same as anterior, but for write position tables static cmsBool WritePositionTable(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number SizeOfTag, cmsUInt32Number Count, cmsUInt32Number BaseOffset, void *Cargo, PositionTableEntryFn ElementFn) { cmsUInt32Number i; cmsUInt32Number DirectoryPos, CurrentPos, Before; cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL; // Create table ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number)); if (ElementOffsets == NULL) goto Error; ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number)); if (ElementSizes == NULL) goto Error; // Keep starting position of curve offsets DirectoryPos = io ->Tell(io); // Write a fake directory to be filled latter on for (i=0; i < Count; i++) { if (!_cmsWriteUInt32Number(io, 0)) goto Error; // Offset if (!_cmsWriteUInt32Number(io, 0)) goto Error; // size } // Write each element. Keep track of the size as well. for (i=0; i < Count; i++) { Before = io ->Tell(io); ElementOffsets[i] = Before - BaseOffset; // Callback to write... if (!ElementFn(self, io, Cargo, i, SizeOfTag)) goto Error; // Now the size ElementSizes[i] = io ->Tell(io) - Before; } // Write the directory CurrentPos = io ->Tell(io); if (!io ->Seek(io, DirectoryPos)) goto Error; for (i=0; i < Count; i++) { if (!_cmsWriteUInt32Number(io, ElementOffsets[i])) goto Error; if (!_cmsWriteUInt32Number(io, ElementSizes[i])) goto Error; } if (!io ->Seek(io, CurrentPos)) goto Error; if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets); if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes); return TRUE; Error: if (ElementOffsets != NULL) _cmsFree(io ->ContextID, ElementOffsets); if (ElementSizes != NULL) _cmsFree(io ->ContextID, ElementSizes); return FALSE; } // ******************************************************************************** // Type XYZ. Only one value is allowed // ******************************************************************************** //The XYZType contains an array of three encoded values for the XYZ tristimulus //values. Tristimulus values must be non-negative. The signed encoding allows for //implementation optimizations by minimizing the number of fixed formats. static void *Type_XYZ_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsCIEXYZ* xyz; *nItems = 0; xyz = (cmsCIEXYZ*) _cmsMallocZero(self ->ContextID, sizeof(cmsCIEXYZ)); if (xyz == NULL) return NULL; if (!_cmsReadXYZNumber(io, xyz)) { _cmsFree(self ->ContextID, xyz); return NULL; } *nItems = 1; return (void*) xyz; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_XYZ_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { return _cmsWriteXYZNumber(io, (cmsCIEXYZ*) Ptr); cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_XYZ_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIEXYZ)); cmsUNUSED_PARAMETER(n); } static void Type_XYZ_Free(struct _cms_typehandler_struct* self, void *Ptr) { _cmsFree(self ->ContextID, Ptr); } static cmsTagTypeSignature DecideXYZtype(cmsFloat64Number ICCVersion, const void *Data) { return cmsSigXYZType; cmsUNUSED_PARAMETER(ICCVersion); cmsUNUSED_PARAMETER(Data); } // ******************************************************************************** // Type chromaticity. Only one value is allowed // ******************************************************************************** // The chromaticity tag type provides basic chromaticity data and type of // phosphors or colorants of a monitor to applications and utilities. static void *Type_Chromaticity_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsCIExyYTRIPLE* chrm; cmsUInt16Number nChans, Table; *nItems = 0; chrm = (cmsCIExyYTRIPLE*) _cmsMallocZero(self ->ContextID, sizeof(cmsCIExyYTRIPLE)); if (chrm == NULL) return NULL; if (!_cmsReadUInt16Number(io, &nChans)) goto Error; // Let's recover from a bug introduced in early versions of lcms1 if (nChans == 0 && SizeOfTag == 32) { if (!_cmsReadUInt16Number(io, NULL)) goto Error; if (!_cmsReadUInt16Number(io, &nChans)) goto Error; } if (nChans != 3) goto Error; if (!_cmsReadUInt16Number(io, &Table)) goto Error; if (!_cmsRead15Fixed16Number(io, &chrm ->Red.x)) goto Error; if (!_cmsRead15Fixed16Number(io, &chrm ->Red.y)) goto Error; chrm ->Red.Y = 1.0; if (!_cmsRead15Fixed16Number(io, &chrm ->Green.x)) goto Error; if (!_cmsRead15Fixed16Number(io, &chrm ->Green.y)) goto Error; chrm ->Green.Y = 1.0; if (!_cmsRead15Fixed16Number(io, &chrm ->Blue.x)) goto Error; if (!_cmsRead15Fixed16Number(io, &chrm ->Blue.y)) goto Error; chrm ->Blue.Y = 1.0; *nItems = 1; return (void*) chrm; Error: _cmsFree(self ->ContextID, (void*) chrm); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool SaveOneChromaticity(cmsFloat64Number x, cmsFloat64Number y, cmsIOHANDLER* io) { if (!_cmsWriteUInt32Number(io, _cmsDoubleTo15Fixed16(x))) return FALSE; if (!_cmsWriteUInt32Number(io, _cmsDoubleTo15Fixed16(y))) return FALSE; return TRUE; } static cmsBool Type_Chromaticity_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsCIExyYTRIPLE* chrm = (cmsCIExyYTRIPLE*) Ptr; if (!_cmsWriteUInt16Number(io, 3)) return FALSE; // nChannels if (!_cmsWriteUInt16Number(io, 0)) return FALSE; // Table if (!SaveOneChromaticity(chrm -> Red.x, chrm -> Red.y, io)) return FALSE; if (!SaveOneChromaticity(chrm -> Green.x, chrm -> Green.y, io)) return FALSE; if (!SaveOneChromaticity(chrm -> Blue.x, chrm -> Blue.y, io)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_Chromaticity_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIExyYTRIPLE)); cmsUNUSED_PARAMETER(n); } static void Type_Chromaticity_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigColorantOrderType // ******************************************************************************** // This is an optional tag which specifies the laydown order in which colorants will // be printed on an n-colorant device. The laydown order may be the same as the // channel generation order listed in the colorantTableTag or the channel order of a // colour space such as CMYK, in which case this tag is not needed. When this is not // the case (for example, ink-towers sometimes use the order KCMY), this tag may be // used to specify the laydown order of the colorants. static void *Type_ColorantOrderType_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt8Number* ColorantOrder; cmsUInt32Number Count; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (Count > cmsMAXCHANNELS) return NULL; ColorantOrder = (cmsUInt8Number*) _cmsCalloc(self ->ContextID, cmsMAXCHANNELS, sizeof(cmsUInt8Number)); if (ColorantOrder == NULL) return NULL; // We use FF as end marker memset(ColorantOrder, 0xFF, cmsMAXCHANNELS * sizeof(cmsUInt8Number)); if (io ->Read(io, ColorantOrder, sizeof(cmsUInt8Number), Count) != Count) { _cmsFree(self ->ContextID, (void*) ColorantOrder); return NULL; } *nItems = 1; return (void*) ColorantOrder; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_ColorantOrderType_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt8Number* ColorantOrder = (cmsUInt8Number*) Ptr; cmsUInt32Number i, sz, Count; // Get the length for (Count=i=0; i < cmsMAXCHANNELS; i++) { if (ColorantOrder[i] != 0xFF) Count++; } if (!_cmsWriteUInt32Number(io, Count)) return FALSE; sz = Count * sizeof(cmsUInt8Number); if (!io -> Write(io, sz, ColorantOrder)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_ColorantOrderType_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, cmsMAXCHANNELS * sizeof(cmsUInt8Number)); cmsUNUSED_PARAMETER(n); } static void Type_ColorantOrderType_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigS15Fixed16ArrayType // ******************************************************************************** // This type represents an array of generic 4-byte/32-bit fixed point quantity. // The number of values is determined from the size of the tag. static void *Type_S15Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsFloat64Number* array_double; cmsUInt32Number i, n; *nItems = 0; n = SizeOfTag / sizeof(cmsUInt32Number); array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number)); if (array_double == NULL) return NULL; for (i=0; i < n; i++) { if (!_cmsRead15Fixed16Number(io, &array_double[i])) { _cmsFree(self ->ContextID, array_double); return NULL; } } *nItems = n; return (void*) array_double; } static cmsBool Type_S15Fixed16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsFloat64Number* Value = (cmsFloat64Number*) Ptr; cmsUInt32Number i; for (i=0; i < nItems; i++) { if (!_cmsWrite15Fixed16Number(io, Value[i])) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(self); } static void* Type_S15Fixed16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsFloat64Number)); } static void Type_S15Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigU16Fixed16ArrayType // ******************************************************************************** // This type represents an array of generic 4-byte/32-bit quantity. // The number of values is determined from the size of the tag. static void *Type_U16Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsFloat64Number* array_double; cmsUInt32Number v; cmsUInt32Number i, n; *nItems = 0; n = SizeOfTag / sizeof(cmsUInt32Number); array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number)); if (array_double == NULL) return NULL; for (i=0; i < n; i++) { if (!_cmsReadUInt32Number(io, &v)) { _cmsFree(self ->ContextID, (void*) array_double); return NULL; } // Convert to cmsFloat64Number array_double[i] = (cmsFloat64Number) (v / 65536.0); } *nItems = n; return (void*) array_double; } static cmsBool Type_U16Fixed16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsFloat64Number* Value = (cmsFloat64Number*) Ptr; cmsUInt32Number i; for (i=0; i < nItems; i++) { cmsUInt32Number v = (cmsUInt32Number) floor(Value[i]*65536.0 + 0.5); if (!_cmsWriteUInt32Number(io, v)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(self); } static void* Type_U16Fixed16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsFloat64Number)); } static void Type_U16Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigSignatureType // ******************************************************************************** // // The signatureType contains a four-byte sequence, Sequences of less than four // characters are padded at the end with spaces, 20h. // Typically this type is used for registered tags that can be displayed on many // development systems as a sequence of four characters. static void *Type_Signature_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsSignature* SigPtr = (cmsSignature*) _cmsMalloc(self ->ContextID, sizeof(cmsSignature)); if (SigPtr == NULL) return NULL; if (!_cmsReadUInt32Number(io, SigPtr)) return NULL; *nItems = 1; return SigPtr; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_Signature_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsSignature* SigPtr = (cmsSignature*) Ptr; return _cmsWriteUInt32Number(io, *SigPtr); cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_Signature_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, n * sizeof(cmsSignature)); } static void Type_Signature_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigTextType // ******************************************************************************** // // The textType is a simple text structure that contains a 7-bit ASCII text string. // The length of the string is obtained by subtracting 8 from the element size portion // of the tag itself. This string must be terminated with a 00h byte. static void *Type_Text_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { char* Text = NULL; cmsMLU* mlu = NULL; // Create a container mlu = cmsMLUalloc(self ->ContextID, 1); if (mlu == NULL) return NULL; *nItems = 0; // We need to store the "\0" at the end, so +1 if (SizeOfTag == UINT_MAX) goto Error; Text = (char*) _cmsMalloc(self ->ContextID, SizeOfTag + 1); if (Text == NULL) goto Error; if (io -> Read(io, Text, sizeof(char), SizeOfTag) != SizeOfTag) goto Error; // Make sure text is properly ended Text[SizeOfTag] = 0; *nItems = 1; // Keep the result if (!cmsMLUsetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text)) goto Error; _cmsFree(self ->ContextID, Text); return (void*) mlu; Error: if (mlu != NULL) cmsMLUfree(mlu); if (Text != NULL) _cmsFree(self ->ContextID, Text); return NULL; } // The conversion implies to choose a language. So, we choose the actual language. static cmsBool Type_Text_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsMLU* mlu = (cmsMLU*) Ptr; cmsUInt32Number size; cmsBool rc; char* Text; // Get the size of the string. Note there is an extra "\0" at the end size = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0); if (size == 0) return FALSE; // Cannot be zero! // Create memory Text = (char*) _cmsMalloc(self ->ContextID, size); if (Text == NULL) return FALSE; cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text, size); // Write it, including separator rc = io ->Write(io, size, Text); _cmsFree(self ->ContextID, Text); return rc; cmsUNUSED_PARAMETER(nItems); } static void* Type_Text_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsMLUdup((cmsMLU*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_Text_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsMLU* mlu = (cmsMLU*) Ptr; cmsMLUfree(mlu); return; cmsUNUSED_PARAMETER(self); } static cmsTagTypeSignature DecideTextType(cmsFloat64Number ICCVersion, const void *Data) { if (ICCVersion >= 4.0) return cmsSigMultiLocalizedUnicodeType; return cmsSigTextType; cmsUNUSED_PARAMETER(Data); } // ******************************************************************************** // Type cmsSigDataType // ******************************************************************************** // General purpose data type static void *Type_Data_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsICCData* BinData; cmsUInt32Number LenOfData; *nItems = 0; if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL; LenOfData = SizeOfTag - sizeof(cmsUInt32Number); if (LenOfData > INT_MAX) return NULL; BinData = (cmsICCData*) _cmsMalloc(self ->ContextID, sizeof(cmsICCData) + LenOfData - 1); if (BinData == NULL) return NULL; BinData ->len = LenOfData; if (!_cmsReadUInt32Number(io, &BinData->flag)) { _cmsFree(self ->ContextID, BinData); return NULL; } if (io -> Read(io, BinData ->data, sizeof(cmsUInt8Number), LenOfData) != LenOfData) { _cmsFree(self ->ContextID, BinData); return NULL; } *nItems = 1; return (void*) BinData; } static cmsBool Type_Data_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsICCData* BinData = (cmsICCData*) Ptr; if (!_cmsWriteUInt32Number(io, BinData ->flag)) return FALSE; return io ->Write(io, BinData ->len, BinData ->data); cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_Data_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { cmsICCData* BinData = (cmsICCData*) Ptr; return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsICCData) + BinData ->len - 1); cmsUNUSED_PARAMETER(n); } static void Type_Data_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigTextDescriptionType // ******************************************************************************** static void *Type_Text_Description_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { char* Text = NULL; cmsMLU* mlu = NULL; cmsUInt32Number AsciiCount; cmsUInt32Number i, UnicodeCode, UnicodeCount; cmsUInt16Number ScriptCodeCode, Dummy; cmsUInt8Number ScriptCodeCount; *nItems = 0; // One dword should be there if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL; // Read len of ASCII if (!_cmsReadUInt32Number(io, &AsciiCount)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); // Check for size if (SizeOfTag < AsciiCount) return NULL; // All seems Ok, allocate the container mlu = cmsMLUalloc(self ->ContextID, 1); if (mlu == NULL) return NULL; // As many memory as size of tag Text = (char*) _cmsMalloc(self ->ContextID, AsciiCount + 1); if (Text == NULL) goto Error; // Read it if (io ->Read(io, Text, sizeof(char), AsciiCount) != AsciiCount) goto Error; SizeOfTag -= AsciiCount; // Make sure there is a terminator Text[AsciiCount] = 0; // Set the MLU entry. From here we can be tolerant to wrong types if (!cmsMLUsetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text)) goto Error; _cmsFree(self ->ContextID, (void*) Text); Text = NULL; // Skip Unicode code if (SizeOfTag < 2* sizeof(cmsUInt32Number)) goto Done; if (!_cmsReadUInt32Number(io, &UnicodeCode)) goto Done; if (!_cmsReadUInt32Number(io, &UnicodeCount)) goto Done; SizeOfTag -= 2* sizeof(cmsUInt32Number); if (SizeOfTag < UnicodeCount*sizeof(cmsUInt16Number)) goto Done; for (i=0; i < UnicodeCount; i++) { if (!io ->Read(io, &Dummy, sizeof(cmsUInt16Number), 1)) goto Done; } SizeOfTag -= UnicodeCount*sizeof(cmsUInt16Number); // Skip ScriptCode code if present. Some buggy profiles does have less // data that stricttly required. We need to skip it as this type may come // embedded in other types. if (SizeOfTag >= sizeof(cmsUInt16Number) + sizeof(cmsUInt8Number) + 67) { if (!_cmsReadUInt16Number(io, &ScriptCodeCode)) goto Done; if (!_cmsReadUInt8Number(io, &ScriptCodeCount)) goto Done; // Skip rest of tag for (i=0; i < 67; i++) { if (!io ->Read(io, &Dummy, sizeof(cmsUInt8Number), 1)) goto Error; } } Done: *nItems = 1; return mlu; Error: if (Text) _cmsFree(self ->ContextID, (void*) Text); if (mlu) cmsMLUfree(mlu); return NULL; } // This tag can come IN UNALIGNED SIZE. In order to prevent issues, we force zeros on description to align it static cmsBool Type_Text_Description_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsMLU* mlu = (cmsMLU*) Ptr; char *Text = NULL; wchar_t *Wide = NULL; cmsUInt32Number len, len_text, len_tag_requirement, len_aligned; cmsBool rc = FALSE; char Filler[68]; // Used below for writting zeroes memset(Filler, 0, sizeof(Filler)); // Get the len of string len = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0); // Specification ICC.1:2001-04 (v2.4.0): It has been found that textDescriptionType can contain misaligned data //(see clause 4.1 for the definition of �aligned�). Because the Unicode language // code and Unicode count immediately follow the ASCII description, their // alignment is not correct if the ASCII count is not a multiple of four. The // ScriptCode code is misaligned when the ASCII count is odd. Profile reading and // writing software must be written carefully in order to handle these alignment // problems. // // The above last sentence suggest to handle alignment issues in the // parser. The provided example (Table 69 on Page 60) makes this clear. // The padding only in the ASCII count is not sufficient for a aligned tag // size, with the same text size in ASCII and Unicode. // Null strings if (len <= 0) { Text = (char*) _cmsDupMem(self ->ContextID, "", sizeof(char)); Wide = (wchar_t*) _cmsDupMem(self ->ContextID, L"", sizeof(wchar_t)); } else { // Create independent buffers Text = (char*) _cmsCalloc(self ->ContextID, len, sizeof(char)); if (Text == NULL) goto Error; Wide = (wchar_t*) _cmsCalloc(self ->ContextID, len, sizeof(wchar_t)); if (Wide == NULL) goto Error; // Get both representations. cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, Text, len * sizeof(char)); cmsMLUgetWide(mlu, cmsNoLanguage, cmsNoCountry, Wide, len * sizeof(wchar_t)); } // Tell the real text len including the null terminator and padding len_text = (cmsUInt32Number) strlen(Text) + 1; // Compute an total tag size requirement len_tag_requirement = (8+4+len_text+4+4+2*len_text+2+1+67); len_aligned = _cmsALIGNLONG(len_tag_requirement); // * cmsUInt32Number count; * Description length // * cmsInt8Number desc[count] * NULL terminated ascii string // * cmsUInt32Number ucLangCode; * UniCode language code // * cmsUInt32Number ucCount; * UniCode description length // * cmsInt16Number ucDesc[ucCount];* The UniCode description // * cmsUInt16Number scCode; * ScriptCode code // * cmsUInt8Number scCount; * ScriptCode count // * cmsInt8Number scDesc[67]; * ScriptCode Description if (!_cmsWriteUInt32Number(io, len_text)) goto Error; if (!io ->Write(io, len_text, Text)) goto Error; if (!_cmsWriteUInt32Number(io, 0)) goto Error; // ucLanguageCode if (!_cmsWriteUInt32Number(io, len_text)) goto Error; // Note that in some compilers sizeof(cmsUInt16Number) != sizeof(wchar_t) if (!_cmsWriteWCharArray(io, len_text, Wide)) goto Error; // ScriptCode Code & count (unused) if (!_cmsWriteUInt16Number(io, 0)) goto Error; if (!_cmsWriteUInt8Number(io, 0)) goto Error; if (!io ->Write(io, 67, Filler)) goto Error; // possibly add pad at the end of tag if(len_aligned - len_tag_requirement > 0) if (!io ->Write(io, len_aligned - len_tag_requirement, Filler)) goto Error; rc = TRUE; Error: if (Text) _cmsFree(self ->ContextID, Text); if (Wide) _cmsFree(self ->ContextID, Wide); return rc; cmsUNUSED_PARAMETER(nItems); } static void* Type_Text_Description_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsMLUdup((cmsMLU*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_Text_Description_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsMLU* mlu = (cmsMLU*) Ptr; cmsMLUfree(mlu); return; cmsUNUSED_PARAMETER(self); } static cmsTagTypeSignature DecideTextDescType(cmsFloat64Number ICCVersion, const void *Data) { if (ICCVersion >= 4.0) return cmsSigMultiLocalizedUnicodeType; return cmsSigTextDescriptionType; cmsUNUSED_PARAMETER(Data); } // ******************************************************************************** // Type cmsSigCurveType // ******************************************************************************** static void *Type_Curve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt32Number Count; cmsToneCurve* NewGamma; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; switch (Count) { case 0: // Linear. { cmsFloat64Number SingleGamma = 1.0; NewGamma = cmsBuildParametricToneCurve(self ->ContextID, 1, &SingleGamma); if (!NewGamma) return NULL; *nItems = 1; return NewGamma; } case 1: // Specified as the exponent of gamma function { cmsUInt16Number SingleGammaFixed; cmsFloat64Number SingleGamma; if (!_cmsReadUInt16Number(io, &SingleGammaFixed)) return NULL; SingleGamma = _cms8Fixed8toDouble(SingleGammaFixed); *nItems = 1; return cmsBuildParametricToneCurve(self ->ContextID, 1, &SingleGamma); } default: // Curve if (Count > 0x7FFF) return NULL; // This is to prevent bad guys for doing bad things NewGamma = cmsBuildTabulatedToneCurve16(self ->ContextID, Count, NULL); if (!NewGamma) return NULL; if (!_cmsReadUInt16Array(io, Count, NewGamma -> Table16)) return NULL; *nItems = 1; return NewGamma; } cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_Curve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsToneCurve* Curve = (cmsToneCurve*) Ptr; if (Curve ->nSegments == 1 && Curve ->Segments[0].Type == 1) { // Single gamma, preserve number cmsUInt16Number SingleGammaFixed = _cmsDoubleTo8Fixed8(Curve ->Segments[0].Params[0]); if (!_cmsWriteUInt32Number(io, 1)) return FALSE; if (!_cmsWriteUInt16Number(io, SingleGammaFixed)) return FALSE; return TRUE; } if (!_cmsWriteUInt32Number(io, Curve ->nEntries)) return FALSE; return _cmsWriteUInt16Array(io, Curve ->nEntries, Curve ->Table16); cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_Curve_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsDupToneCurve((cmsToneCurve*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_Curve_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsToneCurve* gamma = (cmsToneCurve*) Ptr; cmsFreeToneCurve(gamma); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigParametricCurveType // ******************************************************************************** // Decide which curve type to use on writting static cmsTagTypeSignature DecideCurveType(cmsFloat64Number ICCVersion, const void *Data) { cmsToneCurve* Curve = (cmsToneCurve*) Data; if (ICCVersion < 4.0) return cmsSigCurveType; if (Curve ->nSegments != 1) return cmsSigCurveType; // Only 1-segment curves can be saved as parametric if (Curve ->Segments[0].Type < 0) return cmsSigCurveType; // Only non-inverted curves if (Curve ->Segments[0].Type > 5) return cmsSigCurveType; // Only ICC parametric curves return cmsSigParametricCurveType; } static void *Type_ParametricCurve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { static const int ParamsByType[] = { 1, 3, 4, 5, 7 }; cmsFloat64Number Params[10]; cmsUInt16Number Type; int i, n; cmsToneCurve* NewGamma; if (!_cmsReadUInt16Number(io, &Type)) return NULL; if (!_cmsReadUInt16Number(io, NULL)) return NULL; // Reserved if (Type > 4) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown parametric curve type '%d'", Type); return NULL; } memset(Params, 0, sizeof(Params)); n = ParamsByType[Type]; for (i=0; i < n; i++) { if (!_cmsRead15Fixed16Number(io, &Params[i])) return NULL; } NewGamma = cmsBuildParametricToneCurve(self ->ContextID, Type+1, Params); *nItems = 1; return NewGamma; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_ParametricCurve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsToneCurve* Curve = (cmsToneCurve*) Ptr; int i, nParams, typen; static const int ParamsByType[] = { 0, 1, 3, 4, 5, 7 }; typen = Curve -> Segments[0].Type; if (Curve ->nSegments > 1 || typen < 1) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Multisegment or Inverted parametric curves cannot be written"); return FALSE; } if (typen > 5) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported parametric curve"); return FALSE; } nParams = ParamsByType[typen]; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) (Curve ->Segments[0].Type - 1))) return FALSE; if (!_cmsWriteUInt16Number(io, 0)) return FALSE; // Reserved for (i=0; i < nParams; i++) { if (!_cmsWrite15Fixed16Number(io, Curve -> Segments[0].Params[i])) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_ParametricCurve_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsDupToneCurve((cmsToneCurve*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_ParametricCurve_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsToneCurve* gamma = (cmsToneCurve*) Ptr; cmsFreeToneCurve(gamma); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigDateTimeType // ******************************************************************************** // A 12-byte value representation of the time and date, where the byte usage is assigned // as specified in table 1. The actual values are encoded as 16-bit unsigned integers // (uInt16Number - see 5.1.6). // // All the dateTimeNumber values in a profile shall be in Coordinated Universal Time // (UTC, also known as GMT or ZULU Time). Profile writers are required to convert local // time to UTC when setting these values. Programmes that display these values may show // the dateTimeNumber as UTC, show the equivalent local time (at current locale), or // display both UTC and local versions of the dateTimeNumber. static void *Type_DateTime_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsDateTimeNumber timestamp; struct tm * NewDateTime; *nItems = 0; NewDateTime = (struct tm*) _cmsMalloc(self ->ContextID, sizeof(struct tm)); if (NewDateTime == NULL) return NULL; if (io->Read(io, &timestamp, sizeof(cmsDateTimeNumber), 1) != 1) return NULL; _cmsDecodeDateTimeNumber(&timestamp, NewDateTime); *nItems = 1; return NewDateTime; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_DateTime_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { struct tm * DateTime = (struct tm*) Ptr; cmsDateTimeNumber timestamp; _cmsEncodeDateTimeNumber(&timestamp, DateTime); if (!io ->Write(io, sizeof(cmsDateTimeNumber), &timestamp)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_DateTime_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, sizeof(struct tm)); cmsUNUSED_PARAMETER(n); } static void Type_DateTime_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type icMeasurementType // ******************************************************************************** /* The measurementType information refers only to the internal profile data and is meant to provide profile makers an alternative to the default measurement specifications. */ static void *Type_Measurement_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsICCMeasurementConditions mc; memset(&mc, 0, sizeof(mc)); if (!_cmsReadUInt32Number(io, &mc.Observer)) return NULL; if (!_cmsReadXYZNumber(io, &mc.Backing)) return NULL; if (!_cmsReadUInt32Number(io, &mc.Geometry)) return NULL; if (!_cmsRead15Fixed16Number(io, &mc.Flare)) return NULL; if (!_cmsReadUInt32Number(io, &mc.IlluminantType)) return NULL; *nItems = 1; return _cmsDupMem(self ->ContextID, &mc, sizeof(cmsICCMeasurementConditions)); cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_Measurement_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsICCMeasurementConditions* mc =(cmsICCMeasurementConditions*) Ptr; if (!_cmsWriteUInt32Number(io, mc->Observer)) return FALSE; if (!_cmsWriteXYZNumber(io, &mc->Backing)) return FALSE; if (!_cmsWriteUInt32Number(io, mc->Geometry)) return FALSE; if (!_cmsWrite15Fixed16Number(io, mc->Flare)) return FALSE; if (!_cmsWriteUInt32Number(io, mc->IlluminantType)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_Measurement_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsICCMeasurementConditions)); cmsUNUSED_PARAMETER(n); } static void Type_Measurement_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigMultiLocalizedUnicodeType // ******************************************************************************** // // Do NOT trust SizeOfTag as there is an issue on the definition of profileSequenceDescTag. See the TechNote from // Max Derhak and Rohit Patil about this: basically the size of the string table should be guessed and cannot be // taken from the size of tag if this tag is embedded as part of bigger structures (profileSequenceDescTag, for instance) // static void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsMLU* mlu; cmsUInt32Number Count, RecLen, NumOfWchar; cmsUInt32Number SizeOfHeader; cmsUInt32Number Len, Offset; cmsUInt32Number i; wchar_t* Block; cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (!_cmsReadUInt32Number(io, &RecLen)) return NULL; if (RecLen != 12) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported."); return NULL; } mlu = cmsMLUalloc(self ->ContextID, Count); if (mlu == NULL) return NULL; mlu ->UsedEntries = Count; SizeOfHeader = 12 * Count + sizeof(_cmsTagBase); LargestPosition = 0; for (i=0; i < Count; i++) { if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error; if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error; // Now deal with Len and offset. if (!_cmsReadUInt32Number(io, &Len)) goto Error; if (!_cmsReadUInt32Number(io, &Offset)) goto Error; // Check for overflow if (Offset < (SizeOfHeader + 8)) goto Error; // True begin of the string BeginOfThisString = Offset - SizeOfHeader - 8; // Ajust to wchar_t elements mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number); mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number); // To guess maximum size, add offset + len EndOfThisString = BeginOfThisString + Len; if (EndOfThisString > LargestPosition) LargestPosition = EndOfThisString; } // Now read the remaining of tag and fill all strings. Subtract the directory SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number); if (SizeOfTag == 0) { Block = NULL; NumOfWchar = 0; } else { Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag); if (Block == NULL) goto Error; NumOfWchar = SizeOfTag / sizeof(wchar_t); if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error; } mlu ->MemPool = Block; mlu ->PoolSize = SizeOfTag; mlu ->PoolUsed = SizeOfTag; *nItems = 1; return (void*) mlu; Error: if (mlu) cmsMLUfree(mlu); return NULL; } static cmsBool Type_MLU_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsMLU* mlu =(cmsMLU*) Ptr; cmsUInt32Number HeaderSize; cmsUInt32Number Len, Offset; cmsUInt32Number i; if (Ptr == NULL) { // Empty placeholder if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 12)) return FALSE; return TRUE; } if (!_cmsWriteUInt32Number(io, mlu ->UsedEntries)) return FALSE; if (!_cmsWriteUInt32Number(io, 12)) return FALSE; HeaderSize = 12 * mlu ->UsedEntries + sizeof(_cmsTagBase); for (i=0; i < mlu ->UsedEntries; i++) { Len = mlu ->Entries[i].Len; Offset = mlu ->Entries[i].StrW; Len = (Len * sizeof(cmsUInt16Number)) / sizeof(wchar_t); Offset = (Offset * sizeof(cmsUInt16Number)) / sizeof(wchar_t) + HeaderSize + 8; if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Language)) return FALSE; if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Country)) return FALSE; if (!_cmsWriteUInt32Number(io, Len)) return FALSE; if (!_cmsWriteUInt32Number(io, Offset)) return FALSE; } if (!_cmsWriteWCharArray(io, mlu ->PoolUsed / sizeof(wchar_t), (wchar_t*) mlu ->MemPool)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_MLU_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsMLUdup((cmsMLU*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_MLU_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsMLUfree((cmsMLU*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigLut8Type // ******************************************************************************** // Decide which LUT type to use on writting static cmsTagTypeSignature DecideLUTtypeA2B(cmsFloat64Number ICCVersion, const void *Data) { cmsPipeline* Lut = (cmsPipeline*) Data; if (ICCVersion < 4.0) { if (Lut ->SaveAs8Bits) return cmsSigLut8Type; return cmsSigLut16Type; } else { return cmsSigLutAtoBType; } } static cmsTagTypeSignature DecideLUTtypeB2A(cmsFloat64Number ICCVersion, const void *Data) { cmsPipeline* Lut = (cmsPipeline*) Data; if (ICCVersion < 4.0) { if (Lut ->SaveAs8Bits) return cmsSigLut8Type; return cmsSigLut16Type; } else { return cmsSigLutBtoAType; } } /* This structure represents a colour transform using tables of 8-bit precision. This type contains four processing elements: a 3 by 3 matrix (which shall be the identity matrix unless the input colour space is XYZ), a set of one dimensional input tables, a multidimensional lookup table, and a set of one dimensional output tables. Data is processed using these elements via the following sequence: (matrix) -> (1d input tables) -> (multidimensional lookup table - CLUT) -> (1d output tables) Byte Position Field Length (bytes) Content Encoded as... 8 1 Number of Input Channels (i) uInt8Number 9 1 Number of Output Channels (o) uInt8Number 10 1 Number of CLUT grid points (identical for each side) (g) uInt8Number 11 1 Reserved for padding (fill with 00h) 12..15 4 Encoded e00 parameter s15Fixed16Number */ // Read 8 bit tables as gamma functions static cmsBool Read8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels) { cmsUInt8Number* Temp = NULL; int i, j; cmsToneCurve* Tables[cmsMAXCHANNELS]; if (nChannels > cmsMAXCHANNELS) return FALSE; if (nChannels <= 0) return FALSE; memset(Tables, 0, sizeof(Tables)); Temp = (cmsUInt8Number*) _cmsMalloc(ContextID, 256); if (Temp == NULL) return FALSE; for (i=0; i < nChannels; i++) { Tables[i] = cmsBuildTabulatedToneCurve16(ContextID, 256, NULL); if (Tables[i] == NULL) goto Error; } for (i=0; i < nChannels; i++) { if (io ->Read(io, Temp, 256, 1) != 1) goto Error; for (j=0; j < 256; j++) Tables[i]->Table16[j] = (cmsUInt16Number) FROM_8_TO_16(Temp[j]); } _cmsFree(ContextID, Temp); Temp = NULL; if (!cmsPipelineInsertStage(lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, nChannels, Tables))) goto Error; for (i=0; i < nChannels; i++) cmsFreeToneCurve(Tables[i]); return TRUE; Error: for (i=0; i < nChannels; i++) { if (Tables[i]) cmsFreeToneCurve(Tables[i]); } if (Temp) _cmsFree(ContextID, Temp); return FALSE; } static cmsBool Write8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsUInt32Number n, _cmsStageToneCurvesData* Tables) { int j; cmsUInt32Number i; cmsUInt8Number val; for (i=0; i < n; i++) { if (Tables) { // Usual case of identity curves if ((Tables ->TheCurves[i]->nEntries == 2) && (Tables->TheCurves[i]->Table16[0] == 0) && (Tables->TheCurves[i]->Table16[1] == 65535)) { for (j=0; j < 256; j++) { if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) j)) return FALSE; } } else if (Tables ->TheCurves[i]->nEntries != 256) { cmsSignalError(ContextID, cmsERROR_RANGE, "LUT8 needs 256 entries on prelinearization"); return FALSE; } else for (j=0; j < 256; j++) { val = (cmsUInt8Number) FROM_16_TO_8(Tables->TheCurves[i]->Table16[j]); if (!_cmsWriteUInt8Number(io, val)) return FALSE; } } } return TRUE; } // Check overflow static cmsUInt32Number uipow(cmsUInt32Number n, cmsUInt32Number a, cmsUInt32Number b) { cmsUInt32Number rv = 1, rc; if (a == 0) return 0; if (n == 0) return 0; for (; b > 0; b--) { rv *= a; // Check for overflow if (rv > UINT_MAX / a) return (cmsUInt32Number) -1; } rc = rv * n; if (rv != rc / n) return (cmsUInt32Number) -1; return rc; } // That will create a MPE LUT with Matrix, pre tables, CLUT and post tables. // 8 bit lut may be scaled easely to v4 PCS, but we need also to properly adjust // PCS on BToAxx tags and AtoB if abstract. We need to fix input direction. static void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt8Number InputChannels, OutputChannels, CLUTpoints; cmsUInt8Number* Temp = NULL; cmsPipeline* NewLUT = NULL; cmsUInt32Number nTabSize, i; cmsFloat64Number Matrix[3*3]; *nItems = 0; if (!_cmsReadUInt8Number(io, &InputChannels)) goto Error; if (!_cmsReadUInt8Number(io, &OutputChannels)) goto Error; if (!_cmsReadUInt8Number(io, &CLUTpoints)) goto Error; if (CLUTpoints == 1) goto Error; // Impossible value, 0 for no CLUT and then 2 at least // Padding if (!_cmsReadUInt8Number(io, NULL)) goto Error; // Do some checking if (InputChannels > cmsMAXCHANNELS) goto Error; if (OutputChannels > cmsMAXCHANNELS) goto Error; // Allocates an empty Pipeline NewLUT = cmsPipelineAlloc(self ->ContextID, InputChannels, OutputChannels); if (NewLUT == NULL) goto Error; // Read the Matrix if (!_cmsRead15Fixed16Number(io, &Matrix[0])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[1])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[2])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[3])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[4])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[5])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[6])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[7])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[8])) goto Error; // Only operates if not identity... if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_BEGIN, cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL))) goto Error; } // Get input tables if (!Read8bitTables(self ->ContextID, io, NewLUT, InputChannels)) goto Error; // Get 3D CLUT. Check the overflow.... nTabSize = uipow(OutputChannels, CLUTpoints, InputChannels); if (nTabSize == (cmsUInt32Number) -1) goto Error; if (nTabSize > 0) { cmsUInt16Number *PtrW, *T; PtrW = T = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number)); if (T == NULL) goto Error; Temp = (cmsUInt8Number*) _cmsMalloc(self ->ContextID, nTabSize); if (Temp == NULL) { _cmsFree(self ->ContextID, T); goto Error; } if (io ->Read(io, Temp, nTabSize, 1) != 1) { _cmsFree(self ->ContextID, T); _cmsFree(self ->ContextID, Temp); goto Error; } for (i = 0; i < nTabSize; i++) { *PtrW++ = FROM_8_TO_16(Temp[i]); } _cmsFree(self ->ContextID, Temp); Temp = NULL; if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T))) goto Error; _cmsFree(self ->ContextID, T); } // Get output tables if (!Read8bitTables(self ->ContextID, io, NewLUT, OutputChannels)) goto Error; *nItems = 1; return NewLUT; Error: if (NewLUT != NULL) cmsPipelineFree(NewLUT); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // We only allow a specific MPE structure: Matrix plus prelin, plus clut, plus post-lin. static cmsBool Type_LUT8_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt32Number j, nTabSize; cmsUInt8Number val; cmsPipeline* NewLUT = (cmsPipeline*) Ptr; cmsStage* mpe; _cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL; _cmsStageMatrixData* MatMPE = NULL; _cmsStageCLutData* clut = NULL; int clutPoints; // Disassemble the LUT into components. mpe = NewLUT -> Elements; if (mpe ->Type == cmsSigMatrixElemType) { MatMPE = (_cmsStageMatrixData*) mpe ->Data; mpe = mpe -> Next; } if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) { PreMPE = (_cmsStageToneCurvesData*) mpe ->Data; mpe = mpe -> Next; } if (mpe != NULL && mpe ->Type == cmsSigCLutElemType) { clut = (_cmsStageCLutData*) mpe -> Data; mpe = mpe ->Next; } if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) { PostMPE = (_cmsStageToneCurvesData*) mpe ->Data; mpe = mpe -> Next; } // That should be all if (mpe != NULL) { cmsSignalError(mpe->ContextID, cmsERROR_UNKNOWN_EXTENSION, "LUT is not suitable to be saved as LUT8"); return FALSE; } if (clut == NULL) clutPoints = 0; else clutPoints = clut->Params->nSamples[0]; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) NewLUT ->InputChannels)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) NewLUT ->OutputChannels)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) clutPoints)) return FALSE; if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Padding if (MatMPE != NULL) { if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[0])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[1])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[2])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[3])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[4])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[5])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[6])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[7])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[8])) return FALSE; } else { if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE; } // The prelinearization table if (!Write8bitTables(self ->ContextID, io, NewLUT ->InputChannels, PreMPE)) return FALSE; nTabSize = uipow(NewLUT->OutputChannels, clutPoints, NewLUT ->InputChannels); if (nTabSize == (cmsUInt32Number) -1) return FALSE; if (nTabSize > 0) { // The 3D CLUT. if (clut != NULL) { for (j=0; j < nTabSize; j++) { val = (cmsUInt8Number) FROM_16_TO_8(clut ->Tab.T[j]); if (!_cmsWriteUInt8Number(io, val)) return FALSE; } } } // The postlinearization table if (!Write8bitTables(self ->ContextID, io, NewLUT ->OutputChannels, PostMPE)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_LUT8_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsPipelineDup((cmsPipeline*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_LUT8_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsPipelineFree((cmsPipeline*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigLut16Type // ******************************************************************************** // Read 16 bit tables as gamma functions static cmsBool Read16bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels, int nEntries) { int i; cmsToneCurve* Tables[cmsMAXCHANNELS]; // Maybe an empty table? (this is a lcms extension) if (nEntries <= 0) return TRUE; // Check for malicious profiles if (nEntries < 2) return FALSE; if (nChannels > cmsMAXCHANNELS) return FALSE; // Init table to zero memset(Tables, 0, sizeof(Tables)); for (i=0; i < nChannels; i++) { Tables[i] = cmsBuildTabulatedToneCurve16(ContextID, nEntries, NULL); if (Tables[i] == NULL) goto Error; if (!_cmsReadUInt16Array(io, nEntries, Tables[i]->Table16)) goto Error; } // Add the table (which may certainly be an identity, but this is up to the optimizer, not the reading code) if (!cmsPipelineInsertStage(lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, nChannels, Tables))) goto Error; for (i=0; i < nChannels; i++) cmsFreeToneCurve(Tables[i]); return TRUE; Error: for (i=0; i < nChannels; i++) { if (Tables[i]) cmsFreeToneCurve(Tables[i]); } return FALSE; } static cmsBool Write16bitTables(cmsContext ContextID, cmsIOHANDLER* io, _cmsStageToneCurvesData* Tables) { int j; cmsUInt32Number i; cmsUInt16Number val; int nEntries; _cmsAssert(Tables != NULL); nEntries = Tables->TheCurves[0]->nEntries; for (i=0; i < Tables ->nCurves; i++) { for (j=0; j < nEntries; j++) { val = Tables->TheCurves[i]->Table16[j]; if (!_cmsWriteUInt16Number(io, val)) return FALSE; } } return TRUE; cmsUNUSED_PARAMETER(ContextID); } static void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt8Number InputChannels, OutputChannels, CLUTpoints; cmsPipeline* NewLUT = NULL; cmsUInt32Number nTabSize; cmsFloat64Number Matrix[3*3]; cmsUInt16Number InputEntries, OutputEntries; *nItems = 0; if (!_cmsReadUInt8Number(io, &InputChannels)) return NULL; if (!_cmsReadUInt8Number(io, &OutputChannels)) return NULL; if (!_cmsReadUInt8Number(io, &CLUTpoints)) return NULL; // 255 maximum // Padding if (!_cmsReadUInt8Number(io, NULL)) return NULL; // Do some checking if (InputChannels > cmsMAXCHANNELS) goto Error; if (OutputChannels > cmsMAXCHANNELS) goto Error; // Allocates an empty LUT NewLUT = cmsPipelineAlloc(self ->ContextID, InputChannels, OutputChannels); if (NewLUT == NULL) goto Error; // Read the Matrix if (!_cmsRead15Fixed16Number(io, &Matrix[0])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[1])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[2])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[3])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[4])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[5])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[6])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[7])) goto Error; if (!_cmsRead15Fixed16Number(io, &Matrix[8])) goto Error; // Only operates on 3 channels if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL))) goto Error; } if (!_cmsReadUInt16Number(io, &InputEntries)) goto Error; if (!_cmsReadUInt16Number(io, &OutputEntries)) goto Error; if (InputEntries > 0x7FFF || OutputEntries > 0x7FFF) goto Error; if (CLUTpoints == 1) goto Error; // Impossible value, 0 for no CLUT and then 2 at least // Get input tables if (!Read16bitTables(self ->ContextID, io, NewLUT, InputChannels, InputEntries)) goto Error; // Get 3D CLUT nTabSize = uipow(OutputChannels, CLUTpoints, InputChannels); if (nTabSize == (cmsUInt32Number) -1) goto Error; if (nTabSize > 0) { cmsUInt16Number *T; T = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number)); if (T == NULL) goto Error; if (!_cmsReadUInt16Array(io, nTabSize, T)) { _cmsFree(self ->ContextID, T); goto Error; } if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T))) { _cmsFree(self ->ContextID, T); goto Error; } _cmsFree(self ->ContextID, T); } // Get output tables if (!Read16bitTables(self ->ContextID, io, NewLUT, OutputChannels, OutputEntries)) goto Error; *nItems = 1; return NewLUT; Error: if (NewLUT != NULL) cmsPipelineFree(NewLUT); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // We only allow some specific MPE structures: Matrix plus prelin, plus clut, plus post-lin. // Some empty defaults are created for missing parts static cmsBool Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt32Number nTabSize; cmsPipeline* NewLUT = (cmsPipeline*) Ptr; cmsStage* mpe; _cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL; _cmsStageMatrixData* MatMPE = NULL; _cmsStageCLutData* clut = NULL; int i, InputChannels, OutputChannels, clutPoints; // Disassemble the LUT into components. mpe = NewLUT -> Elements; if (mpe != NULL && mpe ->Type == cmsSigMatrixElemType) { MatMPE = (_cmsStageMatrixData*) mpe ->Data; mpe = mpe -> Next; } if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) { PreMPE = (_cmsStageToneCurvesData*) mpe ->Data; mpe = mpe -> Next; } if (mpe != NULL && mpe ->Type == cmsSigCLutElemType) { clut = (_cmsStageCLutData*) mpe -> Data; mpe = mpe ->Next; } if (mpe != NULL && mpe ->Type == cmsSigCurveSetElemType) { PostMPE = (_cmsStageToneCurvesData*) mpe ->Data; mpe = mpe -> Next; } // That should be all if (mpe != NULL) { cmsSignalError(mpe->ContextID, cmsERROR_UNKNOWN_EXTENSION, "LUT is not suitable to be saved as LUT16"); return FALSE; } InputChannels = cmsPipelineInputChannels(NewLUT); OutputChannels = cmsPipelineOutputChannels(NewLUT); if (clut == NULL) clutPoints = 0; else clutPoints = clut->Params->nSamples[0]; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) InputChannels)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) OutputChannels)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) clutPoints)) return FALSE; if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Padding if (MatMPE != NULL) { if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[0])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[1])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[2])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[3])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[4])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[5])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[6])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[7])) return FALSE; if (!_cmsWrite15Fixed16Number(io, MatMPE -> Double[8])) return FALSE; } else { if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 1)) return FALSE; } if (PreMPE != NULL) { if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PreMPE ->TheCurves[0]->nEntries)) return FALSE; } else { if (!_cmsWriteUInt16Number(io, 2)) return FALSE; } if (PostMPE != NULL) { if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PostMPE ->TheCurves[0]->nEntries)) return FALSE; } else { if (!_cmsWriteUInt16Number(io, 2)) return FALSE; } // The prelinearization table if (PreMPE != NULL) { if (!Write16bitTables(self ->ContextID, io, PreMPE)) return FALSE; } else { for (i=0; i < InputChannels; i++) { if (!_cmsWriteUInt16Number(io, 0)) return FALSE; if (!_cmsWriteUInt16Number(io, 0xffff)) return FALSE; } } nTabSize = uipow(OutputChannels, clutPoints, InputChannels); if (nTabSize == (cmsUInt32Number) -1) return FALSE; if (nTabSize > 0) { // The 3D CLUT. if (clut != NULL) { if (!_cmsWriteUInt16Array(io, nTabSize, clut->Tab.T)) return FALSE; } } // The postlinearization table if (PostMPE != NULL) { if (!Write16bitTables(self ->ContextID, io, PostMPE)) return FALSE; } else { for (i=0; i < OutputChannels; i++) { if (!_cmsWriteUInt16Number(io, 0)) return FALSE; if (!_cmsWriteUInt16Number(io, 0xffff)) return FALSE; } } return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_LUT16_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsPipelineDup((cmsPipeline*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_LUT16_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsPipelineFree((cmsPipeline*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigLutAToBType // ******************************************************************************** // V4 stuff. Read matrix for LutAtoB and LutBtoA static cmsStage* ReadMatrix(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset) { cmsFloat64Number dMat[3*3]; cmsFloat64Number dOff[3]; cmsStage* Mat; // Go to address if (!io -> Seek(io, Offset)) return NULL; // Read the Matrix if (!_cmsRead15Fixed16Number(io, &dMat[0])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[1])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[2])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[3])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[4])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[5])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[6])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[7])) return NULL; if (!_cmsRead15Fixed16Number(io, &dMat[8])) return NULL; if (!_cmsRead15Fixed16Number(io, &dOff[0])) return NULL; if (!_cmsRead15Fixed16Number(io, &dOff[1])) return NULL; if (!_cmsRead15Fixed16Number(io, &dOff[2])) return NULL; Mat = cmsStageAllocMatrix(self ->ContextID, 3, 3, dMat, dOff); return Mat; } // V4 stuff. Read CLUT part for LutAtoB and LutBtoA static cmsStage* ReadCLUT(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset, int InputChannels, int OutputChannels) { cmsUInt8Number gridPoints8[cmsMAXCHANNELS]; // Number of grid points in each dimension. cmsUInt32Number GridPoints[cmsMAXCHANNELS], i; cmsUInt8Number Precision; cmsStage* CLUT; _cmsStageCLutData* Data; if (!io -> Seek(io, Offset)) return NULL; if (io -> Read(io, gridPoints8, cmsMAXCHANNELS, 1) != 1) return NULL; for (i=0; i < cmsMAXCHANNELS; i++) { if (gridPoints8[i] == 1) return NULL; // Impossible value, 0 for no CLUT and then 2 at least GridPoints[i] = gridPoints8[i]; } if (!_cmsReadUInt8Number(io, &Precision)) return NULL; if (!_cmsReadUInt8Number(io, NULL)) return NULL; if (!_cmsReadUInt8Number(io, NULL)) return NULL; if (!_cmsReadUInt8Number(io, NULL)) return NULL; CLUT = cmsStageAllocCLut16bitGranular(self ->ContextID, GridPoints, InputChannels, OutputChannels, NULL); if (CLUT == NULL) return NULL; Data = (_cmsStageCLutData*) CLUT ->Data; // Precision can be 1 or 2 bytes if (Precision == 1) { cmsUInt8Number v; for (i=0; i < Data ->nEntries; i++) { if (io ->Read(io, &v, sizeof(cmsUInt8Number), 1) != 1) return NULL; Data ->Tab.T[i] = FROM_8_TO_16(v); } } else if (Precision == 2) { if (!_cmsReadUInt16Array(io, Data->nEntries, Data ->Tab.T)) { cmsStageFree(CLUT); return NULL; } } else { cmsStageFree(CLUT); cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown precision of '%d'", Precision); return NULL; } return CLUT; } static cmsToneCurve* ReadEmbeddedCurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io) { cmsTagTypeSignature BaseType; cmsUInt32Number nItems; BaseType = _cmsReadTypeBase(io); switch (BaseType) { case cmsSigCurveType: return (cmsToneCurve*) Type_Curve_Read(self, io, &nItems, 0); case cmsSigParametricCurveType: return (cmsToneCurve*) Type_ParametricCurve_Read(self, io, &nItems, 0); default: { char String[5]; _cmsTagSignature2String(String, (cmsTagSignature) BaseType); cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve type '%s'", String); } return NULL; } } // Read a set of curves from specific offset static cmsStage* ReadSetOfCurves(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number Offset, cmsUInt32Number nCurves) { cmsToneCurve* Curves[cmsMAXCHANNELS]; cmsUInt32Number i; cmsStage* Lin = NULL; if (nCurves > cmsMAXCHANNELS) return FALSE; if (!io -> Seek(io, Offset)) return FALSE; for (i=0; i < nCurves; i++) Curves[i] = NULL; for (i=0; i < nCurves; i++) { Curves[i] = ReadEmbeddedCurve(self, io); if (Curves[i] == NULL) goto Error; if (!_cmsReadAlignment(io)) goto Error; } Lin = cmsStageAllocToneCurves(self ->ContextID, nCurves, Curves); Error: for (i=0; i < nCurves; i++) cmsFreeToneCurve(Curves[i]); return Lin; } // LutAtoB type // This structure represents a colour transform. The type contains up to five processing // elements which are stored in the AtoBTag tag in the following order: a set of one // dimensional curves, a 3 by 3 matrix with offset terms, a set of one dimensional curves, // a multidimensional lookup table, and a set of one dimensional output curves. // Data are processed using these elements via the following sequence: // //("A" curves) -> (multidimensional lookup table - CLUT) -> ("M" curves) -> (matrix) -> ("B" curves). // /* It is possible to use any or all of these processing elements. At least one processing element must be included.Only the following combinations are allowed: B M - Matrix - B A - CLUT - B A - CLUT - M - Matrix - B */ static void* Type_LUTA2B_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt32Number BaseOffset; cmsUInt8Number inputChan; // Number of input channels cmsUInt8Number outputChan; // Number of output channels cmsUInt32Number offsetB; // Offset to first "B" curve cmsUInt32Number offsetMat; // Offset to matrix cmsUInt32Number offsetM; // Offset to first "M" curve cmsUInt32Number offsetC; // Offset to CLUT cmsUInt32Number offsetA; // Offset to first "A" curve cmsPipeline* NewLUT = NULL; BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); if (!_cmsReadUInt8Number(io, &inputChan)) return NULL; if (!_cmsReadUInt8Number(io, &outputChan)) return NULL; if (!_cmsReadUInt16Number(io, NULL)) return NULL; if (!_cmsReadUInt32Number(io, &offsetB)) return NULL; if (!_cmsReadUInt32Number(io, &offsetMat)) return NULL; if (!_cmsReadUInt32Number(io, &offsetM)) return NULL; if (!_cmsReadUInt32Number(io, &offsetC)) return NULL; if (!_cmsReadUInt32Number(io, &offsetA)) return NULL; // Allocates an empty LUT NewLUT = cmsPipelineAlloc(self ->ContextID, inputChan, outputChan); if (NewLUT == NULL) return NULL; if (offsetA!= 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetA, inputChan))) goto Error; } if (offsetC != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan))) goto Error; } if (offsetM != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetM, outputChan))) goto Error; } if (offsetMat != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadMatrix(self, io, BaseOffset + offsetMat))) goto Error; } if (offsetB != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetB, outputChan))) goto Error; } *nItems = 1; return NewLUT; Error: cmsPipelineFree(NewLUT); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // Write a set of curves static cmsBool WriteMatrix(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsStage* mpe) { _cmsStageMatrixData* m = (_cmsStageMatrixData*) mpe -> Data; // Write the Matrix if (!_cmsWrite15Fixed16Number(io, m -> Double[0])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[1])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[2])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[3])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[4])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[5])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[6])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[7])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Double[8])) return FALSE; if (m ->Offset != NULL) { if (!_cmsWrite15Fixed16Number(io, m -> Offset[0])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Offset[1])) return FALSE; if (!_cmsWrite15Fixed16Number(io, m -> Offset[2])) return FALSE; } else { if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; if (!_cmsWrite15Fixed16Number(io, 0)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(self); } // Write a set of curves static cmsBool WriteSetOfCurves(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsTagTypeSignature Type, cmsStage* mpe) { cmsUInt32Number i, n; cmsTagTypeSignature CurrentType; cmsToneCurve** Curves; n = cmsStageOutputChannels(mpe); Curves = _cmsStageGetPtrToCurveSet(mpe); for (i=0; i < n; i++) { // If this is a table-based curve, use curve type even on V4 CurrentType = Type; if ((Curves[i] ->nSegments == 0)|| ((Curves[i]->nSegments == 2) && (Curves[i] ->Segments[1].Type == 0)) ) CurrentType = cmsSigCurveType; else if (Curves[i] ->Segments[0].Type < 0) CurrentType = cmsSigCurveType; if (!_cmsWriteTypeBase(io, CurrentType)) return FALSE; switch (CurrentType) { case cmsSigCurveType: if (!Type_Curve_Write(self, io, Curves[i], 1)) return FALSE; break; case cmsSigParametricCurveType: if (!Type_ParametricCurve_Write(self, io, Curves[i], 1)) return FALSE; break; default: { char String[5]; _cmsTagSignature2String(String, (cmsTagSignature) Type); cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve type '%s'", String); } return FALSE; } if (!_cmsWriteAlignment(io)) return FALSE; } return TRUE; } static cmsBool WriteCLUT(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt8Number Precision, cmsStage* mpe) { cmsUInt8Number gridPoints[cmsMAXCHANNELS]; // Number of grid points in each dimension. cmsUInt32Number i; _cmsStageCLutData* CLUT = ( _cmsStageCLutData*) mpe -> Data; if (CLUT ->HasFloatValues) { cmsSignalError(self ->ContextID, cmsERROR_NOT_SUITABLE, "Cannot save floating point data, CLUT are 8 or 16 bit only"); return FALSE; } memset(gridPoints, 0, sizeof(gridPoints)); for (i=0; i < (cmsUInt32Number) CLUT ->Params ->nInputs; i++) gridPoints[i] = (cmsUInt8Number) CLUT ->Params ->nSamples[i]; if (!io -> Write(io, cmsMAXCHANNELS*sizeof(cmsUInt8Number), gridPoints)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) Precision)) return FALSE; if (!_cmsWriteUInt8Number(io, 0)) return FALSE; if (!_cmsWriteUInt8Number(io, 0)) return FALSE; if (!_cmsWriteUInt8Number(io, 0)) return FALSE; // Precision can be 1 or 2 bytes if (Precision == 1) { for (i=0; i < CLUT->nEntries; i++) { if (!_cmsWriteUInt8Number(io, FROM_16_TO_8(CLUT->Tab.T[i]))) return FALSE; } } else if (Precision == 2) { if (!_cmsWriteUInt16Array(io, CLUT->nEntries, CLUT ->Tab.T)) return FALSE; } else { cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown precision of '%d'", Precision); return FALSE; } if (!_cmsWriteAlignment(io)) return FALSE; return TRUE; } static cmsBool Type_LUTA2B_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsPipeline* Lut = (cmsPipeline*) Ptr; int inputChan, outputChan; cmsStage *A = NULL, *B = NULL, *M = NULL; cmsStage * Matrix = NULL; cmsStage * CLUT = NULL; cmsUInt32Number offsetB = 0, offsetMat = 0, offsetM = 0, offsetC = 0, offsetA = 0; cmsUInt32Number BaseOffset, DirectoryPos, CurrentPos; // Get the base for all offsets BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); if (Lut ->Elements != NULL) if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCurveSetElemType, &B)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &M, &Matrix, &B)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &A, &CLUT, &B)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 5, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &A, &CLUT, &M, &Matrix, &B)) { cmsSignalError(self->ContextID, cmsERROR_NOT_SUITABLE, "LUT is not suitable to be saved as LutAToB"); return FALSE; } // Get input, output channels inputChan = cmsPipelineInputChannels(Lut); outputChan = cmsPipelineOutputChannels(Lut); // Write channel count if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) inputChan)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) outputChan)) return FALSE; if (!_cmsWriteUInt16Number(io, 0)) return FALSE; // Keep directory to be filled latter DirectoryPos = io ->Tell(io); // Write the directory if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (A != NULL) { offsetA = io ->Tell(io) - BaseOffset; if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, A)) return FALSE; } if (CLUT != NULL) { offsetC = io ->Tell(io) - BaseOffset; if (!WriteCLUT(self, io, Lut ->SaveAs8Bits ? 1 : 2, CLUT)) return FALSE; } if (M != NULL) { offsetM = io ->Tell(io) - BaseOffset; if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, M)) return FALSE; } if (Matrix != NULL) { offsetMat = io ->Tell(io) - BaseOffset; if (!WriteMatrix(self, io, Matrix)) return FALSE; } if (B != NULL) { offsetB = io ->Tell(io) - BaseOffset; if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, B)) return FALSE; } CurrentPos = io ->Tell(io); if (!io ->Seek(io, DirectoryPos)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetB)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetMat)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetM)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetC)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetA)) return FALSE; if (!io ->Seek(io, CurrentPos)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_LUTA2B_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsPipelineDup((cmsPipeline*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_LUTA2B_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsPipelineFree((cmsPipeline*) Ptr); return; cmsUNUSED_PARAMETER(self); } // LutBToA type static void* Type_LUTB2A_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt8Number inputChan; // Number of input channels cmsUInt8Number outputChan; // Number of output channels cmsUInt32Number BaseOffset; // Actual position in file cmsUInt32Number offsetB; // Offset to first "B" curve cmsUInt32Number offsetMat; // Offset to matrix cmsUInt32Number offsetM; // Offset to first "M" curve cmsUInt32Number offsetC; // Offset to CLUT cmsUInt32Number offsetA; // Offset to first "A" curve cmsPipeline* NewLUT = NULL; BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); if (!_cmsReadUInt8Number(io, &inputChan)) return NULL; if (!_cmsReadUInt8Number(io, &outputChan)) return NULL; // Padding if (!_cmsReadUInt16Number(io, NULL)) return NULL; if (!_cmsReadUInt32Number(io, &offsetB)) return NULL; if (!_cmsReadUInt32Number(io, &offsetMat)) return NULL; if (!_cmsReadUInt32Number(io, &offsetM)) return NULL; if (!_cmsReadUInt32Number(io, &offsetC)) return NULL; if (!_cmsReadUInt32Number(io, &offsetA)) return NULL; // Allocates an empty LUT NewLUT = cmsPipelineAlloc(self ->ContextID, inputChan, outputChan); if (NewLUT == NULL) return NULL; if (offsetB != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetB, inputChan))) goto Error; } if (offsetMat != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadMatrix(self, io, BaseOffset + offsetMat))) goto Error; } if (offsetM != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetM, inputChan))) goto Error; } if (offsetC != 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan))) goto Error; } if (offsetA!= 0) { if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetA, outputChan))) goto Error; } *nItems = 1; return NewLUT; Error: cmsPipelineFree(NewLUT); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } /* B B - Matrix - M B - CLUT - A B - Matrix - M - CLUT - A */ static cmsBool Type_LUTB2A_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsPipeline* Lut = (cmsPipeline*) Ptr; int inputChan, outputChan; cmsStage *A = NULL, *B = NULL, *M = NULL; cmsStage *Matrix = NULL; cmsStage *CLUT = NULL; cmsUInt32Number offsetB = 0, offsetMat = 0, offsetM = 0, offsetC = 0, offsetA = 0; cmsUInt32Number BaseOffset, DirectoryPos, CurrentPos; BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCurveSetElemType, &B)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, &B, &Matrix, &M)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &B, &CLUT, &A)) if (!cmsPipelineCheckAndRetreiveStages(Lut, 5, cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &B, &Matrix, &M, &CLUT, &A)) { cmsSignalError(self->ContextID, cmsERROR_NOT_SUITABLE, "LUT is not suitable to be saved as LutBToA"); return FALSE; } inputChan = cmsPipelineInputChannels(Lut); outputChan = cmsPipelineOutputChannels(Lut); if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) inputChan)) return FALSE; if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) outputChan)) return FALSE; if (!_cmsWriteUInt16Number(io, 0)) return FALSE; DirectoryPos = io ->Tell(io); if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (A != NULL) { offsetA = io ->Tell(io) - BaseOffset; if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, A)) return FALSE; } if (CLUT != NULL) { offsetC = io ->Tell(io) - BaseOffset; if (!WriteCLUT(self, io, Lut ->SaveAs8Bits ? 1 : 2, CLUT)) return FALSE; } if (M != NULL) { offsetM = io ->Tell(io) - BaseOffset; if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, M)) return FALSE; } if (Matrix != NULL) { offsetMat = io ->Tell(io) - BaseOffset; if (!WriteMatrix(self, io, Matrix)) return FALSE; } if (B != NULL) { offsetB = io ->Tell(io) - BaseOffset; if (!WriteSetOfCurves(self, io, cmsSigParametricCurveType, B)) return FALSE; } CurrentPos = io ->Tell(io); if (!io ->Seek(io, DirectoryPos)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetB)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetMat)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetM)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetC)) return FALSE; if (!_cmsWriteUInt32Number(io, offsetA)) return FALSE; if (!io ->Seek(io, CurrentPos)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_LUTB2A_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsPipelineDup((cmsPipeline*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_LUTB2A_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsPipelineFree((cmsPipeline*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigColorantTableType // ******************************************************************************** /* The purpose of this tag is to identify the colorants used in the profile by a unique name and set of XYZ or L*a*b* values to give the colorant an unambiguous value. The first colorant listed is the colorant of the first device channel of a lut tag. The second colorant listed is the colorant of the second device channel of a lut tag, and so on. */ static void *Type_ColorantTable_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt32Number i, Count; cmsNAMEDCOLORLIST* List; char Name[34]; cmsUInt16Number PCS[3]; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (Count > cmsMAXCHANNELS) { cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many colorants '%d'", Count); return NULL; } List = cmsAllocNamedColorList(self ->ContextID, Count, 0, "", ""); for (i=0; i < Count; i++) { if (io ->Read(io, Name, 32, 1) != 1) goto Error; Name[33] = 0; if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error; if (!cmsAppendNamedColor(List, Name, PCS, NULL)) goto Error; } *nItems = 1; return List; Error: *nItems = 0; cmsFreeNamedColorList(List); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // Saves a colorant table. It is using the named color structure for simplicity sake static cmsBool Type_ColorantTable_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr; int i, nColors; nColors = cmsNamedColorCount(NamedColorList); if (!_cmsWriteUInt32Number(io, nColors)) return FALSE; for (i=0; i < nColors; i++) { char root[33]; cmsUInt16Number PCS[3]; if (!cmsNamedColorInfo(NamedColorList, i, root, NULL, NULL, PCS, NULL)) return 0; root[32] = 0; if (!io ->Write(io, 32, root)) return FALSE; if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_ColorantTable_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n) { cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr; return (void*) cmsDupNamedColorList(nc); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_ColorantTable_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigNamedColor2Type // ******************************************************************************** // //The namedColor2Type is a count value and array of structures that provide color //coordinates for 7-bit ASCII color names. For each named color, a PCS and optional //device representation of the color are given. Both representations are 16-bit values. //The device representation corresponds to the header�s �color space of data� field. //This representation should be consistent with the �number of device components� //field in the namedColor2Type. If this field is 0, device coordinates are not provided. //The PCS representation corresponds to the header�s PCS field. The PCS representation //is always provided. Color names are fixed-length, 32-byte fields including null //termination. In order to maintain maximum portability, it is strongly recommended //that special characters of the 7-bit ASCII set not be used. static void *Type_NamedColor_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt32Number vendorFlag; // Bottom 16 bits for ICC use cmsUInt32Number count; // Count of named colors cmsUInt32Number nDeviceCoords; // Num of device coordinates char prefix[32]; // Prefix for each color name char suffix[32]; // Suffix for each color name cmsNAMEDCOLORLIST* v; cmsUInt32Number i; *nItems = 0; if (!_cmsReadUInt32Number(io, &vendorFlag)) return NULL; if (!_cmsReadUInt32Number(io, &count)) return NULL; if (!_cmsReadUInt32Number(io, &nDeviceCoords)) return NULL; if (io -> Read(io, prefix, 32, 1) != 1) return NULL; if (io -> Read(io, suffix, 32, 1) != 1) return NULL; prefix[31] = suffix[31] = 0; v = cmsAllocNamedColorList(self ->ContextID, count, nDeviceCoords, prefix, suffix); if (v == NULL) { cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many named colors '%d'", count); return NULL; } if (nDeviceCoords > cmsMAXCHANNELS) { cmsSignalError(self->ContextID, cmsERROR_RANGE, "Too many device coordinates '%d'", nDeviceCoords); return 0; } for (i=0; i < count; i++) { cmsUInt16Number PCS[3]; cmsUInt16Number Colorant[cmsMAXCHANNELS]; char Root[33]; memset(Colorant, 0, sizeof(Colorant)); if (io -> Read(io, Root, 32, 1) != 1) return NULL; Root[32] = 0; // To prevent exploits if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error; if (!_cmsReadUInt16Array(io, nDeviceCoords, Colorant)) goto Error; if (!cmsAppendNamedColor(v, Root, PCS, Colorant)) goto Error; } *nItems = 1; return (void*) v ; Error: cmsFreeNamedColorList(v); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // Saves a named color list into a named color profile static cmsBool Type_NamedColor_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr; char prefix[33]; // Prefix for each color name char suffix[33]; // Suffix for each color name int i, nColors; nColors = cmsNamedColorCount(NamedColorList); if (!_cmsWriteUInt32Number(io, 0)) return FALSE; if (!_cmsWriteUInt32Number(io, nColors)) return FALSE; if (!_cmsWriteUInt32Number(io, NamedColorList ->ColorantCount)) return FALSE; strncpy(prefix, (const char*) NamedColorList->Prefix, 32); strncpy(suffix, (const char*) NamedColorList->Suffix, 32); suffix[32] = prefix[32] = 0; if (!io ->Write(io, 32, prefix)) return FALSE; if (!io ->Write(io, 32, suffix)) return FALSE; for (i=0; i < nColors; i++) { cmsUInt16Number PCS[3]; cmsUInt16Number Colorant[cmsMAXCHANNELS]; char Root[33]; if (!cmsNamedColorInfo(NamedColorList, i, Root, NULL, NULL, PCS, Colorant)) return 0; Root[32] = 0; if (!io ->Write(io, 32 , Root)) return FALSE; if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE; if (!_cmsWriteUInt16Array(io, NamedColorList ->ColorantCount, Colorant)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_NamedColor_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n) { cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) Ptr; return (void*) cmsDupNamedColorList(nc); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_NamedColor_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsFreeNamedColorList((cmsNAMEDCOLORLIST*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigProfileSequenceDescType // ******************************************************************************** // This type is an array of structures, each of which contains information from the // header fields and tags from the original profiles which were combined to create // the final profile. The order of the structures is the order in which the profiles // were combined and includes a structure for the final profile. This provides a // description of the profile sequence from source to destination, // typically used with the DeviceLink profile. static cmsBool ReadEmbeddedText(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU** mlu, cmsUInt32Number SizeOfTag) { cmsTagTypeSignature BaseType; cmsUInt32Number nItems; BaseType = _cmsReadTypeBase(io); switch (BaseType) { case cmsSigTextType: if (*mlu) cmsMLUfree(*mlu); *mlu = (cmsMLU*)Type_Text_Read(self, io, &nItems, SizeOfTag); return (*mlu != NULL); case cmsSigTextDescriptionType: if (*mlu) cmsMLUfree(*mlu); *mlu = (cmsMLU*) Type_Text_Description_Read(self, io, &nItems, SizeOfTag); return (*mlu != NULL); /* TBD: Size is needed for MLU, and we have no idea on which is the available size */ case cmsSigMultiLocalizedUnicodeType: if (*mlu) cmsMLUfree(*mlu); *mlu = (cmsMLU*) Type_MLU_Read(self, io, &nItems, SizeOfTag); return (*mlu != NULL); default: return FALSE; } } static void *Type_ProfileSequenceDesc_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsSEQ* OutSeq; cmsUInt32Number i, Count; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count); if (OutSeq == NULL) return NULL; OutSeq ->n = Count; // Get structures as well for (i=0; i < Count; i++) { cmsPSEQDESC* sec = &OutSeq -> seq[i]; if (!_cmsReadUInt32Number(io, &sec ->deviceMfg)) goto Error; if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error; SizeOfTag -= sizeof(cmsUInt32Number); if (!_cmsReadUInt32Number(io, &sec ->deviceModel)) goto Error; if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error; SizeOfTag -= sizeof(cmsUInt32Number); if (!_cmsReadUInt64Number(io, &sec ->attributes)) goto Error; if (SizeOfTag < sizeof(cmsUInt64Number)) goto Error; SizeOfTag -= sizeof(cmsUInt64Number); if (!_cmsReadUInt32Number(io, (cmsUInt32Number *)&sec ->technology)) goto Error; if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error; SizeOfTag -= sizeof(cmsUInt32Number); if (!ReadEmbeddedText(self, io, &sec ->Manufacturer, SizeOfTag)) goto Error; if (!ReadEmbeddedText(self, io, &sec ->Model, SizeOfTag)) goto Error; } *nItems = 1; return OutSeq; Error: cmsFreeProfileSequenceDescription(OutSeq); return NULL; } // Aux--Embed a text description type. It can be of type text description or multilocalized unicode // and it depends of the version number passed on cmsTagDescriptor structure instead of stack static cmsBool SaveDescription(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* Text) { if (self ->ICCVersion < 0x4000000) { if (!_cmsWriteTypeBase(io, cmsSigTextDescriptionType)) return FALSE; return Type_Text_Description_Write(self, io, Text, 1); } else { if (!_cmsWriteTypeBase(io, cmsSigMultiLocalizedUnicodeType)) return FALSE; return Type_MLU_Write(self, io, Text, 1); } } static cmsBool Type_ProfileSequenceDesc_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsSEQ* Seq = (cmsSEQ*) Ptr; cmsUInt32Number i; if (!_cmsWriteUInt32Number(io, Seq->n)) return FALSE; for (i=0; i < Seq ->n; i++) { cmsPSEQDESC* sec = &Seq -> seq[i]; if (!_cmsWriteUInt32Number(io, sec ->deviceMfg)) return FALSE; if (!_cmsWriteUInt32Number(io, sec ->deviceModel)) return FALSE; if (!_cmsWriteUInt64Number(io, &sec ->attributes)) return FALSE; if (!_cmsWriteUInt32Number(io, sec ->technology)) return FALSE; if (!SaveDescription(self, io, sec ->Manufacturer)) return FALSE; if (!SaveDescription(self, io, sec ->Model)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_ProfileSequenceDesc_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n) { return (void*) cmsDupProfileSequenceDescription((cmsSEQ*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_ProfileSequenceDesc_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsFreeProfileSequenceDescription((cmsSEQ*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigProfileSequenceIdType // ******************************************************************************** /* In certain workflows using ICC Device Link Profiles, it is necessary to identify the original profiles that were combined to create the Device Link Profile. This type is an array of structures, each of which contains information for identification of a profile used in a sequence */ static cmsBool ReadSeqID(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Cargo, cmsUInt32Number n, cmsUInt32Number SizeOfTag) { cmsSEQ* OutSeq = (cmsSEQ*) Cargo; cmsPSEQDESC* seq = &OutSeq ->seq[n]; if (io -> Read(io, seq ->ProfileID.ID8, 16, 1) != 1) return FALSE; if (!ReadEmbeddedText(self, io, &seq ->Description, SizeOfTag)) return FALSE; return TRUE; } static void *Type_ProfileSequenceId_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsSEQ* OutSeq; cmsUInt32Number Count; cmsUInt32Number BaseOffset; *nItems = 0; // Get actual position as a basis for element offsets BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); // Get table count if (!_cmsReadUInt32Number(io, &Count)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); // Allocate an empty structure OutSeq = cmsAllocProfileSequenceDescription(self ->ContextID, Count); if (OutSeq == NULL) return NULL; // Read the position table if (!ReadPositionTable(self, io, Count, BaseOffset, OutSeq, ReadSeqID)) { cmsFreeProfileSequenceDescription(OutSeq); return NULL; } // Success *nItems = 1; return OutSeq; } static cmsBool WriteSeqID(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Cargo, cmsUInt32Number n, cmsUInt32Number SizeOfTag) { cmsSEQ* Seq = (cmsSEQ*) Cargo; if (!io ->Write(io, 16, Seq ->seq[n].ProfileID.ID8)) return FALSE; // Store here the MLU if (!SaveDescription(self, io, Seq ->seq[n].Description)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_ProfileSequenceId_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsSEQ* Seq = (cmsSEQ*) Ptr; cmsUInt32Number BaseOffset; // Keep the base offset BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); // This is the table count if (!_cmsWriteUInt32Number(io, Seq ->n)) return FALSE; // This is the position table and content if (!WritePositionTable(self, io, 0, Seq ->n, BaseOffset, Seq, WriteSeqID)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_ProfileSequenceId_Dup(struct _cms_typehandler_struct* self, const void* Ptr, cmsUInt32Number n) { return (void*) cmsDupProfileSequenceDescription((cmsSEQ*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_ProfileSequenceId_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsFreeProfileSequenceDescription((cmsSEQ*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigUcrBgType // ******************************************************************************** /* This type contains curves representing the under color removal and black generation and a text string which is a general description of the method used for the ucr/bg. */ static void *Type_UcrBg_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUcrBg* n = (cmsUcrBg*) _cmsMallocZero(self ->ContextID, sizeof(cmsUcrBg)); cmsUInt32Number CountUcr, CountBg; char* ASCIIString; *nItems = 0; if (n == NULL) return NULL; // First curve is Under color removal if (!_cmsReadUInt32Number(io, &CountUcr)) return NULL; if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); n ->Ucr = cmsBuildTabulatedToneCurve16(self ->ContextID, CountUcr, NULL); if (n ->Ucr == NULL) return NULL; if (!_cmsReadUInt16Array(io, CountUcr, n ->Ucr->Table16)) return NULL; if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL; SizeOfTag -= CountUcr * sizeof(cmsUInt16Number); // Second curve is Black generation if (!_cmsReadUInt32Number(io, &CountBg)) return NULL; if (SizeOfTag < sizeof(cmsUInt32Number)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); n ->Bg = cmsBuildTabulatedToneCurve16(self ->ContextID, CountBg, NULL); if (n ->Bg == NULL) return NULL; if (!_cmsReadUInt16Array(io, CountBg, n ->Bg->Table16)) return NULL; if (SizeOfTag < CountBg * sizeof(cmsUInt16Number)) return NULL; SizeOfTag -= CountBg * sizeof(cmsUInt16Number); if (SizeOfTag == UINT_MAX) return NULL; // Now comes the text. The length is specified by the tag size n ->Desc = cmsMLUalloc(self ->ContextID, 1); if (n ->Desc == NULL) return NULL; ASCIIString = (char*) _cmsMalloc(self ->ContextID, SizeOfTag + 1); if (io ->Read(io, ASCIIString, sizeof(char), SizeOfTag) != SizeOfTag) return NULL; ASCIIString[SizeOfTag] = 0; cmsMLUsetASCII(n ->Desc, cmsNoLanguage, cmsNoCountry, ASCIIString); _cmsFree(self ->ContextID, ASCIIString); *nItems = 1; return (void*) n; } static cmsBool Type_UcrBg_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUcrBg* Value = (cmsUcrBg*) Ptr; cmsUInt32Number TextSize; char* Text; // First curve is Under color removal if (!_cmsWriteUInt32Number(io, Value ->Ucr ->nEntries)) return FALSE; if (!_cmsWriteUInt16Array(io, Value ->Ucr ->nEntries, Value ->Ucr ->Table16)) return FALSE; // Then black generation if (!_cmsWriteUInt32Number(io, Value ->Bg ->nEntries)) return FALSE; if (!_cmsWriteUInt16Array(io, Value ->Bg ->nEntries, Value ->Bg ->Table16)) return FALSE; // Now comes the text. The length is specified by the tag size TextSize = cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, NULL, 0); Text = (char*) _cmsMalloc(self ->ContextID, TextSize); if (cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, Text, TextSize) != TextSize) return FALSE; if (!io ->Write(io, TextSize, Text)) return FALSE; _cmsFree(self ->ContextID, Text); return TRUE; cmsUNUSED_PARAMETER(nItems); } static void* Type_UcrBg_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { cmsUcrBg* Src = (cmsUcrBg*) Ptr; cmsUcrBg* NewUcrBg = (cmsUcrBg*) _cmsMallocZero(self ->ContextID, sizeof(cmsUcrBg)); if (NewUcrBg == NULL) return NULL; NewUcrBg ->Bg = cmsDupToneCurve(Src ->Bg); NewUcrBg ->Ucr = cmsDupToneCurve(Src ->Ucr); NewUcrBg ->Desc = cmsMLUdup(Src ->Desc); return (void*) NewUcrBg; cmsUNUSED_PARAMETER(n); } static void Type_UcrBg_Free(struct _cms_typehandler_struct* self, void *Ptr) { cmsUcrBg* Src = (cmsUcrBg*) Ptr; if (Src ->Ucr) cmsFreeToneCurve(Src ->Ucr); if (Src ->Bg) cmsFreeToneCurve(Src ->Bg); if (Src ->Desc) cmsMLUfree(Src ->Desc); _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigCrdInfoType // ******************************************************************************** /* This type contains the PostScript product name to which this profile corresponds and the names of the companion CRDs. Recall that a single profile can generate multiple CRDs. It is implemented as a MLU being the language code "PS" and then country varies for each element: nm: PostScript product name #0: Rendering intent 0 CRD name #1: Rendering intent 1 CRD name #2: Rendering intent 2 CRD name #3: Rendering intent 3 CRD name */ // Auxiliary, read an string specified as count + string static cmsBool ReadCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, cmsUInt32Number* SizeOfTag, const char* Section) { cmsUInt32Number Count; char* Text; if (*SizeOfTag < sizeof(cmsUInt32Number)) return FALSE; if (!_cmsReadUInt32Number(io, &Count)) return FALSE; if (Count > UINT_MAX - sizeof(cmsUInt32Number)) return FALSE; if (*SizeOfTag < Count + sizeof(cmsUInt32Number)) return FALSE; Text = (char*) _cmsMalloc(self ->ContextID, Count+1); if (Text == NULL) return FALSE; if (io ->Read(io, Text, sizeof(cmsUInt8Number), Count) != Count) { _cmsFree(self ->ContextID, Text); return FALSE; } Text[Count] = 0; cmsMLUsetASCII(mlu, "PS", Section, Text); _cmsFree(self ->ContextID, Text); *SizeOfTag -= (Count + sizeof(cmsUInt32Number)); return TRUE; } static cmsBool WriteCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, const char* Section) { cmsUInt32Number TextSize; char* Text; TextSize = cmsMLUgetASCII(mlu, "PS", Section, NULL, 0); Text = (char*) _cmsMalloc(self ->ContextID, TextSize); if (!_cmsWriteUInt32Number(io, TextSize)) return FALSE; if (cmsMLUgetASCII(mlu, "PS", Section, Text, TextSize) == 0) return FALSE; if (!io ->Write(io, TextSize, Text)) return FALSE; _cmsFree(self ->ContextID, Text); return TRUE; } static void *Type_CrdInfo_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsMLU* mlu = cmsMLUalloc(self ->ContextID, 5); *nItems = 0; if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "nm")) goto Error; if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#0")) goto Error; if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#1")) goto Error; if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#2")) goto Error; if (!ReadCountAndSting(self, io, mlu, &SizeOfTag, "#3")) goto Error; *nItems = 1; return (void*) mlu; Error: cmsMLUfree(mlu); return NULL; } static cmsBool Type_CrdInfo_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsMLU* mlu = (cmsMLU*) Ptr; if (!WriteCountAndSting(self, io, mlu, "nm")) goto Error; if (!WriteCountAndSting(self, io, mlu, "#0")) goto Error; if (!WriteCountAndSting(self, io, mlu, "#1")) goto Error; if (!WriteCountAndSting(self, io, mlu, "#2")) goto Error; if (!WriteCountAndSting(self, io, mlu, "#3")) goto Error; return TRUE; Error: return FALSE; cmsUNUSED_PARAMETER(nItems); } static void* Type_CrdInfo_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsMLUdup((cmsMLU*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_CrdInfo_Free(struct _cms_typehandler_struct* self, void *Ptr) { cmsMLUfree((cmsMLU*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigScreeningType // ******************************************************************************** // //The screeningType describes various screening parameters including screen //frequency, screening angle, and spot shape. static void *Type_Screening_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsScreening* sc = NULL; cmsUInt32Number i; sc = (cmsScreening*) _cmsMallocZero(self ->ContextID, sizeof(cmsScreening)); if (sc == NULL) return NULL; *nItems = 0; if (!_cmsReadUInt32Number(io, &sc ->Flag)) goto Error; if (!_cmsReadUInt32Number(io, &sc ->nChannels)) goto Error; if (sc ->nChannels > cmsMAXCHANNELS - 1) sc ->nChannels = cmsMAXCHANNELS - 1; for (i=0; i < sc ->nChannels; i++) { if (!_cmsRead15Fixed16Number(io, &sc ->Channels[i].Frequency)) goto Error; if (!_cmsRead15Fixed16Number(io, &sc ->Channels[i].ScreenAngle)) goto Error; if (!_cmsReadUInt32Number(io, &sc ->Channels[i].SpotShape)) goto Error; } *nItems = 1; return (void*) sc; Error: if (sc != NULL) _cmsFree(self ->ContextID, sc); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_Screening_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsScreening* sc = (cmsScreening* ) Ptr; cmsUInt32Number i; if (!_cmsWriteUInt32Number(io, sc ->Flag)) return FALSE; if (!_cmsWriteUInt32Number(io, sc ->nChannels)) return FALSE; for (i=0; i < sc ->nChannels; i++) { if (!_cmsWrite15Fixed16Number(io, sc ->Channels[i].Frequency)) return FALSE; if (!_cmsWrite15Fixed16Number(io, sc ->Channels[i].ScreenAngle)) return FALSE; if (!_cmsWriteUInt32Number(io, sc ->Channels[i].SpotShape)) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_Screening_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsScreening)); cmsUNUSED_PARAMETER(n); } static void Type_Screening_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigViewingConditionsType // ******************************************************************************** // //This type represents a set of viewing condition parameters including: //CIE �absolute� illuminant white point tristimulus values and CIE �absolute� //surround tristimulus values. static void *Type_ViewingConditions_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsICCViewingConditions* vc = NULL; vc = (cmsICCViewingConditions*) _cmsMallocZero(self ->ContextID, sizeof(cmsICCViewingConditions)); if (vc == NULL) return NULL; *nItems = 0; if (!_cmsReadXYZNumber(io, &vc ->IlluminantXYZ)) goto Error; if (!_cmsReadXYZNumber(io, &vc ->SurroundXYZ)) goto Error; if (!_cmsReadUInt32Number(io, &vc ->IlluminantType)) goto Error; *nItems = 1; return (void*) vc; Error: if (vc != NULL) _cmsFree(self ->ContextID, vc); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_ViewingConditions_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsICCViewingConditions* sc = (cmsICCViewingConditions* ) Ptr; if (!_cmsWriteXYZNumber(io, &sc ->IlluminantXYZ)) return FALSE; if (!_cmsWriteXYZNumber(io, &sc ->SurroundXYZ)) return FALSE; if (!_cmsWriteUInt32Number(io, sc ->IlluminantType)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void* Type_ViewingConditions_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return _cmsDupMem(self->ContextID, Ptr, sizeof(cmsICCViewingConditions)); cmsUNUSED_PARAMETER(n); } static void Type_ViewingConditions_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigMultiProcessElementType // ******************************************************************************** static void* GenericMPEdup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsStageDup((cmsStage*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void GenericMPEfree(struct _cms_typehandler_struct* self, void *Ptr) { cmsStageFree((cmsStage*) Ptr); return; cmsUNUSED_PARAMETER(self); } // Each curve is stored in one or more curve segments, with break-points specified between curve segments. // The first curve segment always starts at �Infinity, and the last curve segment always ends at +Infinity. The // first and last curve segments shall be specified in terms of a formula, whereas the other segments shall be // specified either in terms of a formula, or by a sampled curve. // Read an embedded segmented curve static cmsToneCurve* ReadSegmentedCurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io) { cmsCurveSegSignature ElementSig; cmsUInt32Number i, j; cmsUInt16Number nSegments; cmsCurveSegment* Segments; cmsToneCurve* Curve; cmsFloat32Number PrevBreak = -1E22F; // - infinite // Take signature and channels for each element. if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return NULL; // That should be a segmented curve if (ElementSig != cmsSigSegmentedCurve) return NULL; if (!_cmsReadUInt32Number(io, NULL)) return NULL; if (!_cmsReadUInt16Number(io, &nSegments)) return NULL; if (!_cmsReadUInt16Number(io, NULL)) return NULL; if (nSegments < 1) return NULL; Segments = (cmsCurveSegment*) _cmsCalloc(self ->ContextID, nSegments, sizeof(cmsCurveSegment)); if (Segments == NULL) return NULL; // Read breakpoints for (i=0; i < (cmsUInt32Number) nSegments - 1; i++) { Segments[i].x0 = PrevBreak; if (!_cmsReadFloat32Number(io, &Segments[i].x1)) goto Error; PrevBreak = Segments[i].x1; } Segments[nSegments-1].x0 = PrevBreak; Segments[nSegments-1].x1 = 1E22F; // A big cmsFloat32Number number // Read segments for (i=0; i < nSegments; i++) { if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) goto Error; if (!_cmsReadUInt32Number(io, NULL)) goto Error; switch (ElementSig) { case cmsSigFormulaCurveSeg: { cmsUInt16Number Type; cmsUInt32Number ParamsByType[] = {4, 5, 5 }; if (!_cmsReadUInt16Number(io, &Type)) goto Error; if (!_cmsReadUInt16Number(io, NULL)) goto Error; Segments[i].Type = Type + 6; if (Type > 2) goto Error; for (j=0; j < ParamsByType[Type]; j++) { cmsFloat32Number f; if (!_cmsReadFloat32Number(io, &f)) goto Error; Segments[i].Params[j] = f; } } break; case cmsSigSampledCurveSeg: { cmsUInt32Number Count; if (!_cmsReadUInt32Number(io, &Count)) return NULL; Segments[i].nGridPoints = Count; Segments[i].SampledPoints = (cmsFloat32Number*) _cmsCalloc(self ->ContextID, Count, sizeof(cmsFloat32Number)); if (Segments[i].SampledPoints == NULL) goto Error; for (j=0; j < Count; j++) { if (!_cmsReadFloat32Number(io, &Segments[i].SampledPoints[j])) goto Error; } } break; default: { char String[5]; _cmsTagSignature2String(String, (cmsTagSignature) ElementSig); cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown curve element type '%s' found.", String); } return NULL; } } Curve = cmsBuildSegmentedToneCurve(self ->ContextID, nSegments, Segments); for (i=0; i < nSegments; i++) { if (Segments[i].SampledPoints) _cmsFree(self ->ContextID, Segments[i].SampledPoints); } _cmsFree(self ->ContextID, Segments); return Curve; Error: if (Segments) _cmsFree(self ->ContextID, Segments); return NULL; } static cmsBool ReadMPECurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Cargo, cmsUInt32Number n, cmsUInt32Number SizeOfTag) { cmsToneCurve** GammaTables = ( cmsToneCurve**) Cargo; GammaTables[n] = ReadSegmentedCurve(self, io); return (GammaTables[n] != NULL); cmsUNUSED_PARAMETER(SizeOfTag); } static void *Type_MPEcurve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsStage* mpe = NULL; cmsUInt16Number InputChans, OutputChans; cmsUInt32Number i, BaseOffset; cmsToneCurve** GammaTables; *nItems = 0; // Get actual position as a basis for element offsets BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); if (!_cmsReadUInt16Number(io, &InputChans)) return NULL; if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL; if (InputChans != OutputChans) return NULL; GammaTables = (cmsToneCurve**) _cmsCalloc(self ->ContextID, InputChans, sizeof(cmsToneCurve*)); if (GammaTables == NULL) return NULL; if (ReadPositionTable(self, io, InputChans, BaseOffset, GammaTables, ReadMPECurve)) { mpe = cmsStageAllocToneCurves(self ->ContextID, InputChans, GammaTables); } else { mpe = NULL; } for (i=0; i < InputChans; i++) { if (GammaTables[i]) cmsFreeToneCurve(GammaTables[i]); } _cmsFree(self ->ContextID, GammaTables); *nItems = (mpe != NULL) ? 1 : 0; return mpe; cmsUNUSED_PARAMETER(SizeOfTag); } // Write a single segmented curve. NO CHECK IS PERFORMED ON VALIDITY static cmsBool WriteSegmentedCurve(cmsIOHANDLER* io, cmsToneCurve* g) { cmsUInt32Number i, j; cmsCurveSegment* Segments = g ->Segments; cmsUInt32Number nSegments = g ->nSegments; if (!_cmsWriteUInt32Number(io, cmsSigSegmentedCurve)) goto Error; if (!_cmsWriteUInt32Number(io, 0)) goto Error; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) nSegments)) goto Error; if (!_cmsWriteUInt16Number(io, 0)) goto Error; // Write the break-points for (i=0; i < nSegments - 1; i++) { if (!_cmsWriteFloat32Number(io, Segments[i].x1)) goto Error; } // Write the segments for (i=0; i < g ->nSegments; i++) { cmsCurveSegment* ActualSeg = Segments + i; if (ActualSeg -> Type == 0) { // This is a sampled curve if (!_cmsWriteUInt32Number(io, (cmsUInt32Number) cmsSigSampledCurveSeg)) goto Error; if (!_cmsWriteUInt32Number(io, 0)) goto Error; if (!_cmsWriteUInt32Number(io, ActualSeg -> nGridPoints)) goto Error; for (j=0; j < g ->Segments[i].nGridPoints; j++) { if (!_cmsWriteFloat32Number(io, ActualSeg -> SampledPoints[j])) goto Error; } } else { int Type; cmsUInt32Number ParamsByType[] = { 4, 5, 5 }; // This is a formula-based if (!_cmsWriteUInt32Number(io, (cmsUInt32Number) cmsSigFormulaCurveSeg)) goto Error; if (!_cmsWriteUInt32Number(io, 0)) goto Error; // We only allow 1, 2 and 3 as types Type = ActualSeg ->Type - 6; if (Type > 2 || Type < 0) goto Error; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) Type)) goto Error; if (!_cmsWriteUInt16Number(io, 0)) goto Error; for (j=0; j < ParamsByType[Type]; j++) { if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) ActualSeg ->Params[j])) goto Error; } } // It seems there is no need to align. Code is here, and for safety commented out // if (!_cmsWriteAlignment(io)) goto Error; } return TRUE; Error: return FALSE; } static cmsBool WriteMPECurve(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Cargo, cmsUInt32Number n, cmsUInt32Number SizeOfTag) { _cmsStageToneCurvesData* Curves = (_cmsStageToneCurvesData*) Cargo; return WriteSegmentedCurve(io, Curves ->TheCurves[n]); cmsUNUSED_PARAMETER(SizeOfTag); cmsUNUSED_PARAMETER(self); } // Write a curve, checking first for validity static cmsBool Type_MPEcurve_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt32Number BaseOffset; cmsStage* mpe = (cmsStage*) Ptr; _cmsStageToneCurvesData* Curves = (_cmsStageToneCurvesData*) mpe ->Data; BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); // Write the header. Since those are curves, input and output channels are same if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE; if (!WritePositionTable(self, io, 0, mpe ->InputChannels, BaseOffset, Curves, WriteMPECurve)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); } // The matrix is organized as an array of PxQ+Q elements, where P is the number of input channels to the // matrix, and Q is the number of output channels. The matrix elements are each float32Numbers. The array // is organized as follows: // array = [e11, e12, �, e1P, e21, e22, �, e2P, �, eQ1, eQ2, �, eQP, e1, e2, �, eQ] static void *Type_MPEmatrix_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsStage* mpe; cmsUInt16Number InputChans, OutputChans; cmsUInt32Number nElems, i; cmsFloat64Number* Matrix; cmsFloat64Number* Offsets; if (!_cmsReadUInt16Number(io, &InputChans)) return NULL; if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL; nElems = InputChans * OutputChans; // Input and output chans may be ANY (up to 0xffff) Matrix = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, nElems, sizeof(cmsFloat64Number)); if (Matrix == NULL) return NULL; Offsets = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, OutputChans, sizeof(cmsFloat64Number)); if (Offsets == NULL) { _cmsFree(self ->ContextID, Matrix); return NULL; } for (i=0; i < nElems; i++) { cmsFloat32Number v; if (!_cmsReadFloat32Number(io, &v)) return NULL; Matrix[i] = v; } for (i=0; i < OutputChans; i++) { cmsFloat32Number v; if (!_cmsReadFloat32Number(io, &v)) return NULL; Offsets[i] = v; } mpe = cmsStageAllocMatrix(self ->ContextID, OutputChans, InputChans, Matrix, Offsets); _cmsFree(self ->ContextID, Matrix); _cmsFree(self ->ContextID, Offsets); *nItems = 1; return mpe; cmsUNUSED_PARAMETER(SizeOfTag); } static cmsBool Type_MPEmatrix_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt32Number i, nElems; cmsStage* mpe = (cmsStage*) Ptr; _cmsStageMatrixData* Matrix = (_cmsStageMatrixData*) mpe ->Data; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->OutputChannels)) return FALSE; nElems = mpe ->InputChannels * mpe ->OutputChannels; for (i=0; i < nElems; i++) { if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) Matrix->Double[i])) return FALSE; } for (i=0; i < mpe ->OutputChannels; i++) { if (Matrix ->Offset == NULL) { if (!_cmsWriteFloat32Number(io, 0)) return FALSE; } else { if (!_cmsWriteFloat32Number(io, (cmsFloat32Number) Matrix->Offset[i])) return FALSE; } } return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } static void *Type_MPEclut_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsStage* mpe = NULL; cmsUInt16Number InputChans, OutputChans; cmsUInt8Number Dimensions8[16]; cmsUInt32Number i, nMaxGrids, GridPoints[MAX_INPUT_DIMENSIONS]; _cmsStageCLutData* clut; if (!_cmsReadUInt16Number(io, &InputChans)) return NULL; if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL; if (InputChans == 0) goto Error; if (OutputChans == 0) goto Error; if (io ->Read(io, Dimensions8, sizeof(cmsUInt8Number), 16) != 16) goto Error; // Copy MAX_INPUT_DIMENSIONS at most. Expand to cmsUInt32Number nMaxGrids = InputChans > MAX_INPUT_DIMENSIONS ? MAX_INPUT_DIMENSIONS : InputChans; for (i=0; i < nMaxGrids; i++) GridPoints[i] = (cmsUInt32Number) Dimensions8[i]; // Allocate the true CLUT mpe = cmsStageAllocCLutFloatGranular(self ->ContextID, GridPoints, InputChans, OutputChans, NULL); if (mpe == NULL) goto Error; // Read the data clut = (_cmsStageCLutData*) mpe ->Data; for (i=0; i < clut ->nEntries; i++) { if (!_cmsReadFloat32Number(io, &clut ->Tab.TFloat[i])) goto Error; } *nItems = 1; return mpe; Error: *nItems = 0; if (mpe != NULL) cmsStageFree(mpe); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // Write a CLUT in floating point static cmsBool Type_MPEclut_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt8Number Dimensions8[16]; // 16 because the spec says 16 and not max number of channels cmsUInt32Number i; cmsStage* mpe = (cmsStage*) Ptr; _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe ->Data; // Check for maximum number of channels supported by lcms if (mpe -> InputChannels > MAX_INPUT_DIMENSIONS) return FALSE; // Only floats are supported in MPE if (clut ->HasFloatValues == FALSE) return FALSE; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->InputChannels)) return FALSE; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) mpe ->OutputChannels)) return FALSE; memset(Dimensions8, 0, sizeof(Dimensions8)); for (i=0; i < mpe ->InputChannels; i++) Dimensions8[i] = (cmsUInt8Number) clut ->Params ->nSamples[i]; if (!io ->Write(io, 16, Dimensions8)) return FALSE; for (i=0; i < clut ->nEntries; i++) { if (!_cmsWriteFloat32Number(io, clut ->Tab.TFloat[i])) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } // This is the list of built-in MPE types static _cmsTagTypeLinkedList SupportedMPEtypes[] = { {{ (cmsTagTypeSignature) cmsSigBAcsElemType, NULL, NULL, NULL, NULL, NULL, 0 }, &SupportedMPEtypes[1] }, // Ignore those elements for now {{ (cmsTagTypeSignature) cmsSigEAcsElemType, NULL, NULL, NULL, NULL, NULL, 0 }, &SupportedMPEtypes[2] }, // (That's what the spec says) {TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCurveSetElemType, MPEcurve), &SupportedMPEtypes[3] }, {TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigMatrixElemType, MPEmatrix), &SupportedMPEtypes[4] }, {TYPE_MPE_HANDLER((cmsTagTypeSignature) cmsSigCLutElemType, MPEclut), NULL }, }; _cmsTagTypePluginChunkType _cmsMPETypePluginChunk = { NULL }; static cmsBool ReadMPEElem(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Cargo, cmsUInt32Number n, cmsUInt32Number SizeOfTag) { cmsStageSignature ElementSig; cmsTagTypeHandler* TypeHandler; cmsUInt32Number nItems; cmsPipeline *NewLUT = (cmsPipeline *) Cargo; _cmsTagTypePluginChunkType* MPETypePluginChunk = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(self->ContextID, MPEPlugin); // Take signature and channels for each element. if (!_cmsReadUInt32Number(io, (cmsUInt32Number*) &ElementSig)) return FALSE; // The reserved placeholder if (!_cmsReadUInt32Number(io, NULL)) return FALSE; // Read diverse MPE types TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, MPETypePluginChunk ->TagTypes, SupportedMPEtypes); if (TypeHandler == NULL) { char String[5]; _cmsTagSignature2String(String, (cmsTagSignature) ElementSig); // An unknown element was found. cmsSignalError(self ->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown MPE type '%s' found.", String); return FALSE; } // If no read method, just ignore the element (valid for cmsSigBAcsElemType and cmsSigEAcsElemType) // Read the MPE. No size is given if (TypeHandler ->ReadPtr != NULL) { // This is a real element which should be read and processed if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, (cmsStage*) TypeHandler ->ReadPtr(self, io, &nItems, SizeOfTag))) return FALSE; } return TRUE; cmsUNUSED_PARAMETER(SizeOfTag); cmsUNUSED_PARAMETER(n); } // This is the main dispatcher for MPE static void *Type_MPE_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt16Number InputChans, OutputChans; cmsUInt32Number ElementCount; cmsPipeline *NewLUT = NULL; cmsUInt32Number BaseOffset; // Get actual position as a basis for element offsets BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); // Read channels and element count if (!_cmsReadUInt16Number(io, &InputChans)) return NULL; if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL; // Allocates an empty LUT NewLUT = cmsPipelineAlloc(self ->ContextID, InputChans, OutputChans); if (NewLUT == NULL) return NULL; if (!_cmsReadUInt32Number(io, &ElementCount)) return NULL; if (!ReadPositionTable(self, io, ElementCount, BaseOffset, NewLUT, ReadMPEElem)) { if (NewLUT != NULL) cmsPipelineFree(NewLUT); *nItems = 0; return NULL; } // Success *nItems = 1; return NewLUT; cmsUNUSED_PARAMETER(SizeOfTag); } // This one is a liitle bit more complex, so we don't use position tables this time. static cmsBool Type_MPE_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsUInt32Number i, BaseOffset, DirectoryPos, CurrentPos; int inputChan, outputChan; cmsUInt32Number ElemCount; cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL, Before; cmsStageSignature ElementSig; cmsPipeline* Lut = (cmsPipeline*) Ptr; cmsStage* Elem = Lut ->Elements; cmsTagTypeHandler* TypeHandler; _cmsTagTypePluginChunkType* MPETypePluginChunk = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(self->ContextID, MPEPlugin); BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); inputChan = cmsPipelineInputChannels(Lut); outputChan = cmsPipelineOutputChannels(Lut); ElemCount = cmsPipelineStageCount(Lut); ElementOffsets = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number)); if (ElementOffsets == NULL) goto Error; ElementSizes = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number)); if (ElementSizes == NULL) goto Error; // Write the head if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) inputChan)) goto Error; if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) outputChan)) goto Error; if (!_cmsWriteUInt32Number(io, (cmsUInt16Number) ElemCount)) goto Error; DirectoryPos = io ->Tell(io); // Write a fake directory to be filled latter on for (i=0; i < ElemCount; i++) { if (!_cmsWriteUInt32Number(io, 0)) goto Error; // Offset if (!_cmsWriteUInt32Number(io, 0)) goto Error; // size } // Write each single tag. Keep track of the size as well. for (i=0; i < ElemCount; i++) { ElementOffsets[i] = io ->Tell(io) - BaseOffset; ElementSig = Elem ->Type; TypeHandler = GetHandler((cmsTagTypeSignature) ElementSig, MPETypePluginChunk->TagTypes, SupportedMPEtypes); if (TypeHandler == NULL) { char String[5]; _cmsTagSignature2String(String, (cmsTagSignature) ElementSig); // An unknow element was found. cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Found unknown MPE type '%s'", String); goto Error; } if (!_cmsWriteUInt32Number(io, ElementSig)) goto Error; if (!_cmsWriteUInt32Number(io, 0)) goto Error; Before = io ->Tell(io); if (!TypeHandler ->WritePtr(self, io, Elem, 1)) goto Error; if (!_cmsWriteAlignment(io)) goto Error; ElementSizes[i] = io ->Tell(io) - Before; Elem = Elem ->Next; } // Write the directory CurrentPos = io ->Tell(io); if (!io ->Seek(io, DirectoryPos)) goto Error; for (i=0; i < ElemCount; i++) { if (!_cmsWriteUInt32Number(io, ElementOffsets[i])) goto Error; if (!_cmsWriteUInt32Number(io, ElementSizes[i])) goto Error; } if (!io ->Seek(io, CurrentPos)) goto Error; if (ElementOffsets != NULL) _cmsFree(self ->ContextID, ElementOffsets); if (ElementSizes != NULL) _cmsFree(self ->ContextID, ElementSizes); return TRUE; Error: if (ElementOffsets != NULL) _cmsFree(self ->ContextID, ElementOffsets); if (ElementSizes != NULL) _cmsFree(self ->ContextID, ElementSizes); return FALSE; cmsUNUSED_PARAMETER(nItems); } static void* Type_MPE_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsPipelineDup((cmsPipeline*) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_MPE_Free(struct _cms_typehandler_struct* self, void *Ptr) { cmsPipelineFree((cmsPipeline*) Ptr); return; cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type cmsSigVcgtType // ******************************************************************************** #define cmsVideoCardGammaTableType 0 #define cmsVideoCardGammaFormulaType 1 // Used internally typedef struct { double Gamma; double Min; double Max; } _cmsVCGTGAMMA; static void *Type_vcgt_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsUInt32Number TagType, n, i; cmsToneCurve** Curves; *nItems = 0; // Read tag type if (!_cmsReadUInt32Number(io, &TagType)) return NULL; // Allocate space for the array Curves = ( cmsToneCurve**) _cmsCalloc(self ->ContextID, 3, sizeof(cmsToneCurve*)); if (Curves == NULL) return NULL; // There are two possible flavors switch (TagType) { // Gamma is stored as a table case cmsVideoCardGammaTableType: { cmsUInt16Number nChannels, nElems, nBytes; // Check channel count, which should be 3 (we don't support monochrome this time) if (!_cmsReadUInt16Number(io, &nChannels)) goto Error; if (nChannels != 3) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported number of channels for VCGT '%d'", nChannels); goto Error; } // Get Table element count and bytes per element if (!_cmsReadUInt16Number(io, &nElems)) goto Error; if (!_cmsReadUInt16Number(io, &nBytes)) goto Error; // Adobe's quirk fixup. Fixing broken profiles... if (nElems == 256 && nBytes == 1 && SizeOfTag == 1576) nBytes = 2; // Populate tone curves for (n=0; n < 3; n++) { Curves[n] = cmsBuildTabulatedToneCurve16(self ->ContextID, nElems, NULL); if (Curves[n] == NULL) goto Error; // On depending on byte depth switch (nBytes) { // One byte, 0..255 case 1: for (i=0; i < nElems; i++) { cmsUInt8Number v; if (!_cmsReadUInt8Number(io, &v)) goto Error; Curves[n] ->Table16[i] = FROM_8_TO_16(v); } break; // One word 0..65535 case 2: if (!_cmsReadUInt16Array(io, nElems, Curves[n]->Table16)) goto Error; break; // Unsupported default: cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported bit depth for VCGT '%d'", nBytes * 8); goto Error; } } // For all 3 channels } break; // In this case, gamma is stored as a formula case cmsVideoCardGammaFormulaType: { _cmsVCGTGAMMA Colorant[3]; // Populate tone curves for (n=0; n < 3; n++) { double Params[10]; if (!_cmsRead15Fixed16Number(io, &Colorant[n].Gamma)) goto Error; if (!_cmsRead15Fixed16Number(io, &Colorant[n].Min)) goto Error; if (!_cmsRead15Fixed16Number(io, &Colorant[n].Max)) goto Error; // Parametric curve type 5 is: // Y = (aX + b)^Gamma + e | X >= d // Y = cX + f | X < d // vcgt formula is: // Y = (Max � Min) * (X ^ Gamma) + Min // So, the translation is // a = (Max � Min) ^ ( 1 / Gamma) // e = Min // b=c=d=f=0 Params[0] = Colorant[n].Gamma; Params[1] = pow((Colorant[n].Max - Colorant[n].Min), (1.0 / Colorant[n].Gamma)); Params[2] = 0; Params[3] = 0; Params[4] = 0; Params[5] = Colorant[n].Min; Params[6] = 0; Curves[n] = cmsBuildParametricToneCurve(self ->ContextID, 5, Params); if (Curves[n] == NULL) goto Error; } } break; // Unsupported default: cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported tag type for VCGT '%d'", TagType); goto Error; } *nItems = 1; return (void*) Curves; // Regret, free all resources Error: cmsFreeToneCurveTriple(Curves); _cmsFree(self ->ContextID, Curves); return NULL; cmsUNUSED_PARAMETER(SizeOfTag); } // We don't support all flavors, only 16bits tables and formula static cmsBool Type_vcgt_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsToneCurve** Curves = (cmsToneCurve**) Ptr; cmsUInt32Number i, j; if (cmsGetToneCurveParametricType(Curves[0]) == 5 && cmsGetToneCurveParametricType(Curves[1]) == 5 && cmsGetToneCurveParametricType(Curves[2]) == 5) { if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaFormulaType)) return FALSE; // Save parameters for (i=0; i < 3; i++) { _cmsVCGTGAMMA v; v.Gamma = Curves[i] ->Segments[0].Params[0]; v.Min = Curves[i] ->Segments[0].Params[5]; v.Max = pow(Curves[i] ->Segments[0].Params[1], v.Gamma) + v.Min; if (!_cmsWrite15Fixed16Number(io, v.Gamma)) return FALSE; if (!_cmsWrite15Fixed16Number(io, v.Min)) return FALSE; if (!_cmsWrite15Fixed16Number(io, v.Max)) return FALSE; } } else { // Always store as a table of 256 words if (!_cmsWriteUInt32Number(io, cmsVideoCardGammaTableType)) return FALSE; if (!_cmsWriteUInt16Number(io, 3)) return FALSE; if (!_cmsWriteUInt16Number(io, 256)) return FALSE; if (!_cmsWriteUInt16Number(io, 2)) return FALSE; for (i=0; i < 3; i++) { for (j=0; j < 256; j++) { cmsFloat32Number v = cmsEvalToneCurveFloat(Curves[i], (cmsFloat32Number) (j / 255.0)); cmsUInt16Number n = _cmsQuickSaturateWord(v * 65535.0); if (!_cmsWriteUInt16Number(io, n)) return FALSE; } } } return TRUE; cmsUNUSED_PARAMETER(self); cmsUNUSED_PARAMETER(nItems); } static void* Type_vcgt_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { cmsToneCurve** OldCurves = (cmsToneCurve**) Ptr; cmsToneCurve** NewCurves; NewCurves = ( cmsToneCurve**) _cmsCalloc(self ->ContextID, 3, sizeof(cmsToneCurve*)); if (NewCurves == NULL) return NULL; NewCurves[0] = cmsDupToneCurve(OldCurves[0]); NewCurves[1] = cmsDupToneCurve(OldCurves[1]); NewCurves[2] = cmsDupToneCurve(OldCurves[2]); return (void*) NewCurves; cmsUNUSED_PARAMETER(n); } static void Type_vcgt_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsFreeToneCurveTriple((cmsToneCurve**) Ptr); _cmsFree(self ->ContextID, Ptr); } // ******************************************************************************** // Type cmsSigDictType // ******************************************************************************** // Single column of the table can point to wchar or MLUC elements. Holds arrays of data typedef struct { cmsContext ContextID; cmsUInt32Number *Offsets; cmsUInt32Number *Sizes; } _cmsDICelem; typedef struct { _cmsDICelem Name, Value, DisplayName, DisplayValue; } _cmsDICarray; // Allocate an empty array element static cmsBool AllocElem(cmsContext ContextID, _cmsDICelem* e, cmsUInt32Number Count) { e->Offsets = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number)); if (e->Offsets == NULL) return FALSE; e->Sizes = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number)); if (e->Sizes == NULL) { _cmsFree(ContextID, e -> Offsets); return FALSE; } e ->ContextID = ContextID; return TRUE; } // Free an array element static void FreeElem(_cmsDICelem* e) { if (e ->Offsets != NULL) _cmsFree(e -> ContextID, e -> Offsets); if (e ->Sizes != NULL) _cmsFree(e -> ContextID, e -> Sizes); e->Offsets = e ->Sizes = NULL; } // Get rid of whole array static void FreeArray( _cmsDICarray* a) { if (a ->Name.Offsets != NULL) FreeElem(&a->Name); if (a ->Value.Offsets != NULL) FreeElem(&a ->Value); if (a ->DisplayName.Offsets != NULL) FreeElem(&a->DisplayName); if (a ->DisplayValue.Offsets != NULL) FreeElem(&a ->DisplayValue); } // Allocate whole array static cmsBool AllocArray(cmsContext ContextID, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length) { // Empty values memset(a, 0, sizeof(_cmsDICarray)); // On depending on record size, create column arrays if (!AllocElem(ContextID, &a ->Name, Count)) goto Error; if (!AllocElem(ContextID, &a ->Value, Count)) goto Error; if (Length > 16) { if (!AllocElem(ContextID, &a -> DisplayName, Count)) goto Error; } if (Length > 24) { if (!AllocElem(ContextID, &a ->DisplayValue, Count)) goto Error; } return TRUE; Error: FreeArray(a); return FALSE; } // Read one element static cmsBool ReadOneElem(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, cmsUInt32Number BaseOffset) { if (!_cmsReadUInt32Number(io, &e->Offsets[i])) return FALSE; if (!_cmsReadUInt32Number(io, &e ->Sizes[i])) return FALSE; // An offset of zero has special meaning and shal be preserved if (e ->Offsets[i] > 0) e ->Offsets[i] += BaseOffset; return TRUE; } static cmsBool ReadOffsetArray(cmsIOHANDLER* io, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length, cmsUInt32Number BaseOffset) { cmsUInt32Number i; // Read column arrays for (i=0; i < Count; i++) { if (!ReadOneElem(io, &a -> Name, i, BaseOffset)) return FALSE; if (!ReadOneElem(io, &a -> Value, i, BaseOffset)) return FALSE; if (Length > 16) { if (!ReadOneElem(io, &a ->DisplayName, i, BaseOffset)) return FALSE; } if (Length > 24) { if (!ReadOneElem(io, & a -> DisplayValue, i, BaseOffset)) return FALSE; } } return TRUE; } // Write one element static cmsBool WriteOneElem(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i) { if (!_cmsWriteUInt32Number(io, e->Offsets[i])) return FALSE; if (!_cmsWriteUInt32Number(io, e ->Sizes[i])) return FALSE; return TRUE; } static cmsBool WriteOffsetArray(cmsIOHANDLER* io, _cmsDICarray* a, cmsUInt32Number Count, cmsUInt32Number Length) { cmsUInt32Number i; for (i=0; i < Count; i++) { if (!WriteOneElem(io, &a -> Name, i)) return FALSE; if (!WriteOneElem(io, &a -> Value, i)) return FALSE; if (Length > 16) { if (!WriteOneElem(io, &a -> DisplayName, i)) return FALSE; } if (Length > 24) { if (!WriteOneElem(io, &a -> DisplayValue, i)) return FALSE; } } return TRUE; } static cmsBool ReadOneWChar(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, wchar_t ** wcstr) { cmsUInt32Number nChars; // Special case for undefined strings (see ICC Votable // Proposal Submission, Dictionary Type and Metadata TAG Definition) if (e -> Offsets[i] == 0) { *wcstr = NULL; return TRUE; } if (!io -> Seek(io, e -> Offsets[i])) return FALSE; nChars = e ->Sizes[i] / sizeof(cmsUInt16Number); *wcstr = (wchar_t*) _cmsMallocZero(e ->ContextID, (nChars + 1) * sizeof(wchar_t)); if (*wcstr == NULL) return FALSE; if (!_cmsReadWCharArray(io, nChars, *wcstr)) { _cmsFree(e ->ContextID, *wcstr); return FALSE; } // End of string marker (*wcstr)[nChars] = 0; return TRUE; } static cmsUInt32Number mywcslen(const wchar_t *s) { const wchar_t *p; p = s; while (*p) p++; return (cmsUInt32Number)(p - s); } static cmsBool WriteOneWChar(cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, const wchar_t * wcstr, cmsUInt32Number BaseOffset) { cmsUInt32Number Before = io ->Tell(io); cmsUInt32Number n; e ->Offsets[i] = Before - BaseOffset; if (wcstr == NULL) { e ->Sizes[i] = 0; e ->Offsets[i] = 0; return TRUE; } n = mywcslen(wcstr); if (!_cmsWriteWCharArray(io, n, wcstr)) return FALSE; e ->Sizes[i] = io ->Tell(io) - Before; return TRUE; } static cmsBool ReadOneMLUC(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, cmsMLU** mlu) { cmsUInt32Number nItems = 0; // A way to get null MLUCs if (e -> Offsets[i] == 0 || e ->Sizes[i] == 0) { *mlu = NULL; return TRUE; } if (!io -> Seek(io, e -> Offsets[i])) return FALSE; *mlu = (cmsMLU*) Type_MLU_Read(self, io, &nItems, e ->Sizes[i]); return *mlu != NULL; } static cmsBool WriteOneMLUC(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, _cmsDICelem* e, cmsUInt32Number i, const cmsMLU* mlu, cmsUInt32Number BaseOffset) { cmsUInt32Number Before; // Special case for undefined strings (see ICC Votable // Proposal Submission, Dictionary Type and Metadata TAG Definition) if (mlu == NULL) { e ->Sizes[i] = 0; e ->Offsets[i] = 0; return TRUE; } Before = io ->Tell(io); e ->Offsets[i] = Before - BaseOffset; if (!Type_MLU_Write(self, io, (void*) mlu, 1)) return FALSE; e ->Sizes[i] = io ->Tell(io) - Before; return TRUE; } static void *Type_Dictionary_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsHANDLE hDict; cmsUInt32Number i, Count, Length; cmsUInt32Number BaseOffset; _cmsDICarray a; wchar_t *NameWCS = NULL, *ValueWCS = NULL; cmsMLU *DisplayNameMLU = NULL, *DisplayValueMLU=NULL; cmsBool rc; *nItems = 0; // Get actual position as a basis for element offsets BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); // Get name-value record count if (!_cmsReadUInt32Number(io, &Count)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); // Get rec length if (!_cmsReadUInt32Number(io, &Length)) return NULL; SizeOfTag -= sizeof(cmsUInt32Number); // Check for valid lengths if (Length != 16 && Length != 24 && Length != 32) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unknown record length in dictionary '%d'", Length); return NULL; } // Creates an empty dictionary hDict = cmsDictAlloc(self -> ContextID); if (hDict == NULL) return NULL; // On depending on record size, create column arrays if (!AllocArray(self -> ContextID, &a, Count, Length)) goto Error; // Read column arrays if (!ReadOffsetArray(io, &a, Count, Length, BaseOffset)) goto Error; // Seek to each element and read it for (i=0; i < Count; i++) { if (!ReadOneWChar(io, &a.Name, i, &NameWCS)) goto Error; if (!ReadOneWChar(io, &a.Value, i, &ValueWCS)) goto Error; if (Length > 16) { if (!ReadOneMLUC(self, io, &a.DisplayName, i, &DisplayNameMLU)) goto Error; } if (Length > 24) { if (!ReadOneMLUC(self, io, &a.DisplayValue, i, &DisplayValueMLU)) goto Error; } if (NameWCS == NULL || ValueWCS == NULL) { cmsSignalError(self->ContextID, cmsERROR_CORRUPTION_DETECTED, "Bad dictionary Name/Value"); rc = FALSE; } else { rc = cmsDictAddEntry(hDict, NameWCS, ValueWCS, DisplayNameMLU, DisplayValueMLU); } if (NameWCS != NULL) _cmsFree(self ->ContextID, NameWCS); if (ValueWCS != NULL) _cmsFree(self ->ContextID, ValueWCS); if (DisplayNameMLU != NULL) cmsMLUfree(DisplayNameMLU); if (DisplayValueMLU != NULL) cmsMLUfree(DisplayValueMLU); if (!rc) goto Error; } FreeArray(&a); *nItems = 1; return (void*) hDict; Error: FreeArray(&a); cmsDictFree(hDict); return NULL; } static cmsBool Type_Dictionary_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsHANDLE hDict = (cmsHANDLE) Ptr; const cmsDICTentry* p; cmsBool AnyName, AnyValue; cmsUInt32Number i, Count, Length; cmsUInt32Number DirectoryPos, CurrentPos, BaseOffset; _cmsDICarray a; if (hDict == NULL) return FALSE; BaseOffset = io ->Tell(io) - sizeof(_cmsTagBase); // Let's inspect the dictionary Count = 0; AnyName = FALSE; AnyValue = FALSE; for (p = cmsDictGetEntryList(hDict); p != NULL; p = cmsDictNextEntry(p)) { if (p ->DisplayName != NULL) AnyName = TRUE; if (p ->DisplayValue != NULL) AnyValue = TRUE; Count++; } Length = 16; if (AnyName) Length += 8; if (AnyValue) Length += 8; if (!_cmsWriteUInt32Number(io, Count)) return FALSE; if (!_cmsWriteUInt32Number(io, Length)) return FALSE; // Keep starting position of offsets table DirectoryPos = io ->Tell(io); // Allocate offsets array if (!AllocArray(self ->ContextID, &a, Count, Length)) goto Error; // Write a fake directory to be filled latter on if (!WriteOffsetArray(io, &a, Count, Length)) goto Error; // Write each element. Keep track of the size as well. p = cmsDictGetEntryList(hDict); for (i=0; i < Count; i++) { if (!WriteOneWChar(io, &a.Name, i, p ->Name, BaseOffset)) goto Error; if (!WriteOneWChar(io, &a.Value, i, p ->Value, BaseOffset)) goto Error; if (p ->DisplayName != NULL) { if (!WriteOneMLUC(self, io, &a.DisplayName, i, p ->DisplayName, BaseOffset)) goto Error; } if (p ->DisplayValue != NULL) { if (!WriteOneMLUC(self, io, &a.DisplayValue, i, p ->DisplayValue, BaseOffset)) goto Error; } p = cmsDictNextEntry(p); } // Write the directory CurrentPos = io ->Tell(io); if (!io ->Seek(io, DirectoryPos)) goto Error; if (!WriteOffsetArray(io, &a, Count, Length)) goto Error; if (!io ->Seek(io, CurrentPos)) goto Error; FreeArray(&a); return TRUE; Error: FreeArray(&a); return FALSE; cmsUNUSED_PARAMETER(nItems); } static void* Type_Dictionary_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n) { return (void*) cmsDictDup((cmsHANDLE) Ptr); cmsUNUSED_PARAMETER(n); cmsUNUSED_PARAMETER(self); } static void Type_Dictionary_Free(struct _cms_typehandler_struct* self, void* Ptr) { cmsDictFree((cmsHANDLE) Ptr); cmsUNUSED_PARAMETER(self); } // ******************************************************************************** // Type support main routines // ******************************************************************************** // This is the list of built-in types static _cmsTagTypeLinkedList SupportedTagTypes[] = { {TYPE_HANDLER(cmsSigChromaticityType, Chromaticity), &SupportedTagTypes[1] }, {TYPE_HANDLER(cmsSigColorantOrderType, ColorantOrderType), &SupportedTagTypes[2] }, {TYPE_HANDLER(cmsSigS15Fixed16ArrayType, S15Fixed16), &SupportedTagTypes[3] }, {TYPE_HANDLER(cmsSigU16Fixed16ArrayType, U16Fixed16), &SupportedTagTypes[4] }, {TYPE_HANDLER(cmsSigTextType, Text), &SupportedTagTypes[5] }, {TYPE_HANDLER(cmsSigTextDescriptionType, Text_Description), &SupportedTagTypes[6] }, {TYPE_HANDLER(cmsSigCurveType, Curve), &SupportedTagTypes[7] }, {TYPE_HANDLER(cmsSigParametricCurveType, ParametricCurve), &SupportedTagTypes[8] }, {TYPE_HANDLER(cmsSigDateTimeType, DateTime), &SupportedTagTypes[9] }, {TYPE_HANDLER(cmsSigLut8Type, LUT8), &SupportedTagTypes[10] }, {TYPE_HANDLER(cmsSigLut16Type, LUT16), &SupportedTagTypes[11] }, {TYPE_HANDLER(cmsSigColorantTableType, ColorantTable), &SupportedTagTypes[12] }, {TYPE_HANDLER(cmsSigNamedColor2Type, NamedColor), &SupportedTagTypes[13] }, {TYPE_HANDLER(cmsSigMultiLocalizedUnicodeType, MLU), &SupportedTagTypes[14] }, {TYPE_HANDLER(cmsSigProfileSequenceDescType, ProfileSequenceDesc), &SupportedTagTypes[15] }, {TYPE_HANDLER(cmsSigSignatureType, Signature), &SupportedTagTypes[16] }, {TYPE_HANDLER(cmsSigMeasurementType, Measurement), &SupportedTagTypes[17] }, {TYPE_HANDLER(cmsSigDataType, Data), &SupportedTagTypes[18] }, {TYPE_HANDLER(cmsSigLutAtoBType, LUTA2B), &SupportedTagTypes[19] }, {TYPE_HANDLER(cmsSigLutBtoAType, LUTB2A), &SupportedTagTypes[20] }, {TYPE_HANDLER(cmsSigUcrBgType, UcrBg), &SupportedTagTypes[21] }, {TYPE_HANDLER(cmsSigCrdInfoType, CrdInfo), &SupportedTagTypes[22] }, {TYPE_HANDLER(cmsSigMultiProcessElementType, MPE), &SupportedTagTypes[23] }, {TYPE_HANDLER(cmsSigScreeningType, Screening), &SupportedTagTypes[24] }, {TYPE_HANDLER(cmsSigViewingConditionsType, ViewingConditions), &SupportedTagTypes[25] }, {TYPE_HANDLER(cmsSigXYZType, XYZ), &SupportedTagTypes[26] }, {TYPE_HANDLER(cmsCorbisBrokenXYZtype, XYZ), &SupportedTagTypes[27] }, {TYPE_HANDLER(cmsMonacoBrokenCurveType, Curve), &SupportedTagTypes[28] }, {TYPE_HANDLER(cmsSigProfileSequenceIdType, ProfileSequenceId), &SupportedTagTypes[29] }, {TYPE_HANDLER(cmsSigDictType, Dictionary), &SupportedTagTypes[30] }, {TYPE_HANDLER(cmsSigVcgtType, vcgt), NULL } }; _cmsTagTypePluginChunkType _cmsTagTypePluginChunk = { NULL }; // Duplicates the zone of memory used by the plug-in in the new context static void DupTagTypeList(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src, int loc) { _cmsTagTypePluginChunkType newHead = { NULL }; _cmsTagTypeLinkedList* entry; _cmsTagTypeLinkedList* Anterior = NULL; _cmsTagTypePluginChunkType* head = (_cmsTagTypePluginChunkType*) src->chunks[loc]; // Walk the list copying all nodes for (entry = head->TagTypes; entry != NULL; entry = entry ->Next) { _cmsTagTypeLinkedList *newEntry = ( _cmsTagTypeLinkedList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTagTypeLinkedList)); if (newEntry == NULL) return; // We want to keep the linked list order, so this is a little bit tricky newEntry -> Next = NULL; if (Anterior) Anterior -> Next = newEntry; Anterior = newEntry; if (newHead.TagTypes == NULL) newHead.TagTypes = newEntry; } ctx ->chunks[loc] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTagTypePluginChunkType)); } void _cmsAllocTagTypePluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src) { if (src != NULL) { // Duplicate the LIST DupTagTypeList(ctx, src, TagTypePlugin); } else { static _cmsTagTypePluginChunkType TagTypePluginChunk = { NULL }; ctx ->chunks[TagTypePlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagTypePluginChunk, sizeof(_cmsTagTypePluginChunkType)); } } void _cmsAllocMPETypePluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src) { if (src != NULL) { // Duplicate the LIST DupTagTypeList(ctx, src, MPEPlugin); } else { static _cmsTagTypePluginChunkType TagTypePluginChunk = { NULL }; ctx ->chunks[MPEPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagTypePluginChunk, sizeof(_cmsTagTypePluginChunkType)); } } // Both kind of plug-ins share same structure cmsBool _cmsRegisterTagTypePlugin(cmsContext id, cmsPluginBase* Data) { return RegisterTypesPlugin(id, Data, TagTypePlugin); } cmsBool _cmsRegisterMultiProcessElementPlugin(cmsContext id, cmsPluginBase* Data) { return RegisterTypesPlugin(id, Data,MPEPlugin); } // Wrapper for tag types cmsTagTypeHandler* _cmsGetTagTypeHandler(cmsContext ContextID, cmsTagTypeSignature sig) { _cmsTagTypePluginChunkType* ctx = ( _cmsTagTypePluginChunkType*) _cmsContextGetClientChunk(ContextID, TagTypePlugin); return GetHandler(sig, ctx->TagTypes, SupportedTagTypes); } // ******************************************************************************** // Tag support main routines // ******************************************************************************** typedef struct _cmsTagLinkedList_st { cmsTagSignature Signature; cmsTagDescriptor Descriptor; struct _cmsTagLinkedList_st* Next; } _cmsTagLinkedList; // This is the list of built-in tags static _cmsTagLinkedList SupportedTags[] = { { cmsSigAToB0Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[1]}, { cmsSigAToB1Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[2]}, { cmsSigAToB2Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutAtoBType, cmsSigLut8Type}, DecideLUTtypeA2B}, &SupportedTags[3]}, { cmsSigBToA0Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[4]}, { cmsSigBToA1Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[5]}, { cmsSigBToA2Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type}, DecideLUTtypeB2A}, &SupportedTags[6]}, // Allow corbis and its broken XYZ type { cmsSigRedColorantTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[7]}, { cmsSigGreenColorantTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[8]}, { cmsSigBlueColorantTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, DecideXYZtype}, &SupportedTags[9]}, { cmsSigRedTRCTag, { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[10]}, { cmsSigGreenTRCTag, { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[11]}, { cmsSigBlueTRCTag, { 1, 3, { cmsSigCurveType, cmsSigParametricCurveType, cmsMonacoBrokenCurveType }, DecideCurveType}, &SupportedTags[12]}, { cmsSigCalibrationDateTimeTag, { 1, 1, { cmsSigDateTimeType }, NULL}, &SupportedTags[13]}, { cmsSigCharTargetTag, { 1, 1, { cmsSigTextType }, NULL}, &SupportedTags[14]}, { cmsSigChromaticAdaptationTag, { 9, 1, { cmsSigS15Fixed16ArrayType }, NULL}, &SupportedTags[15]}, { cmsSigChromaticityTag, { 1, 1, { cmsSigChromaticityType }, NULL}, &SupportedTags[16]}, { cmsSigColorantOrderTag, { 1, 1, { cmsSigColorantOrderType }, NULL}, &SupportedTags[17]}, { cmsSigColorantTableTag, { 1, 1, { cmsSigColorantTableType }, NULL}, &SupportedTags[18]}, { cmsSigColorantTableOutTag, { 1, 1, { cmsSigColorantTableType }, NULL}, &SupportedTags[19]}, { cmsSigCopyrightTag, { 1, 3, { cmsSigTextType, cmsSigMultiLocalizedUnicodeType, cmsSigTextDescriptionType}, DecideTextType}, &SupportedTags[20]}, { cmsSigDateTimeTag, { 1, 1, { cmsSigDateTimeType }, NULL}, &SupportedTags[21]}, { cmsSigDeviceMfgDescTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[22]}, { cmsSigDeviceModelDescTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[23]}, { cmsSigGamutTag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[24]}, { cmsSigGrayTRCTag, { 1, 2, { cmsSigCurveType, cmsSigParametricCurveType }, DecideCurveType}, &SupportedTags[25]}, { cmsSigLuminanceTag, { 1, 1, { cmsSigXYZType }, NULL}, &SupportedTags[26]}, { cmsSigMediaBlackPointTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, NULL}, &SupportedTags[27]}, { cmsSigMediaWhitePointTag, { 1, 2, { cmsSigXYZType, cmsCorbisBrokenXYZtype }, NULL}, &SupportedTags[28]}, { cmsSigNamedColor2Tag, { 1, 1, { cmsSigNamedColor2Type }, NULL}, &SupportedTags[29]}, { cmsSigPreview0Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[30]}, { cmsSigPreview1Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[31]}, { cmsSigPreview2Tag, { 1, 3, { cmsSigLut16Type, cmsSigLutBtoAType, cmsSigLut8Type }, DecideLUTtypeB2A}, &SupportedTags[32]}, { cmsSigProfileDescriptionTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[33]}, { cmsSigProfileSequenceDescTag, { 1, 1, { cmsSigProfileSequenceDescType }, NULL}, &SupportedTags[34]}, { cmsSigTechnologyTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[35]}, { cmsSigColorimetricIntentImageStateTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[36]}, { cmsSigPerceptualRenderingIntentGamutTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[37]}, { cmsSigSaturationRenderingIntentGamutTag, { 1, 1, { cmsSigSignatureType }, NULL}, &SupportedTags[38]}, { cmsSigMeasurementTag, { 1, 1, { cmsSigMeasurementType }, NULL}, &SupportedTags[39]}, { cmsSigPs2CRD0Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[40]}, { cmsSigPs2CRD1Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[41]}, { cmsSigPs2CRD2Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[42]}, { cmsSigPs2CRD3Tag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[43]}, { cmsSigPs2CSATag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[44]}, { cmsSigPs2RenderingIntentTag, { 1, 1, { cmsSigDataType }, NULL}, &SupportedTags[45]}, { cmsSigViewingCondDescTag, { 1, 3, { cmsSigTextDescriptionType, cmsSigMultiLocalizedUnicodeType, cmsSigTextType}, DecideTextDescType}, &SupportedTags[46]}, { cmsSigUcrBgTag, { 1, 1, { cmsSigUcrBgType}, NULL}, &SupportedTags[47]}, { cmsSigCrdInfoTag, { 1, 1, { cmsSigCrdInfoType}, NULL}, &SupportedTags[48]}, { cmsSigDToB0Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[49]}, { cmsSigDToB1Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[50]}, { cmsSigDToB2Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[51]}, { cmsSigDToB3Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[52]}, { cmsSigBToD0Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[53]}, { cmsSigBToD1Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[54]}, { cmsSigBToD2Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[55]}, { cmsSigBToD3Tag, { 1, 1, { cmsSigMultiProcessElementType}, NULL}, &SupportedTags[56]}, { cmsSigScreeningDescTag, { 1, 1, { cmsSigTextDescriptionType }, NULL}, &SupportedTags[57]}, { cmsSigViewingConditionsTag, { 1, 1, { cmsSigViewingConditionsType }, NULL}, &SupportedTags[58]}, { cmsSigScreeningTag, { 1, 1, { cmsSigScreeningType}, NULL }, &SupportedTags[59]}, { cmsSigVcgtTag, { 1, 1, { cmsSigVcgtType}, NULL }, &SupportedTags[60]}, { cmsSigMetaTag, { 1, 1, { cmsSigDictType}, NULL }, &SupportedTags[61]}, { cmsSigProfileSequenceIdTag, { 1, 1, { cmsSigProfileSequenceIdType}, NULL }, &SupportedTags[62]}, { cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, &SupportedTags[63]}, { cmsSigArgyllArtsTag, { 9, 1, { cmsSigS15Fixed16ArrayType}, NULL}, NULL} }; /* Not supported Why ======================= ========================================= cmsSigOutputResponseTag ==> WARNING, POSSIBLE PATENT ON THIS SUBJECT! cmsSigNamedColorTag ==> Deprecated cmsSigDataTag ==> Ancient, unused cmsSigDeviceSettingsTag ==> Deprecated, useless */ _cmsTagPluginChunkType _cmsTagPluginChunk = { NULL }; // Duplicates the zone of memory used by the plug-in in the new context static void DupTagList(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src) { _cmsTagPluginChunkType newHead = { NULL }; _cmsTagLinkedList* entry; _cmsTagLinkedList* Anterior = NULL; _cmsTagPluginChunkType* head = (_cmsTagPluginChunkType*) src->chunks[TagPlugin]; // Walk the list copying all nodes for (entry = head->Tag; entry != NULL; entry = entry ->Next) { _cmsTagLinkedList *newEntry = ( _cmsTagLinkedList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsTagLinkedList)); if (newEntry == NULL) return; // We want to keep the linked list order, so this is a little bit tricky newEntry -> Next = NULL; if (Anterior) Anterior -> Next = newEntry; Anterior = newEntry; if (newHead.Tag == NULL) newHead.Tag = newEntry; } ctx ->chunks[TagPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTagPluginChunkType)); } void _cmsAllocTagPluginChunk(struct _cmsContext_struct* ctx, const struct _cmsContext_struct* src) { if (src != NULL) { DupTagList(ctx, src); } else { static _cmsTagPluginChunkType TagPluginChunk = { NULL }; ctx ->chunks[TagPlugin] = _cmsSubAllocDup(ctx ->MemPool, &TagPluginChunk, sizeof(_cmsTagPluginChunkType)); } } cmsBool _cmsRegisterTagPlugin(cmsContext id, cmsPluginBase* Data) { cmsPluginTag* Plugin = (cmsPluginTag*) Data; _cmsTagLinkedList *pt; _cmsTagPluginChunkType* TagPluginChunk = ( _cmsTagPluginChunkType*) _cmsContextGetClientChunk(id, TagPlugin); if (Data == NULL) { TagPluginChunk->Tag = NULL; return TRUE; } pt = (_cmsTagLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagLinkedList)); if (pt == NULL) return FALSE; pt ->Signature = Plugin ->Signature; pt ->Descriptor = Plugin ->Descriptor; pt ->Next = TagPluginChunk ->Tag; TagPluginChunk ->Tag = pt; return TRUE; } // Return a descriptor for a given tag or NULL cmsTagDescriptor* _cmsGetTagDescriptor(cmsContext ContextID, cmsTagSignature sig) { _cmsTagLinkedList* pt; _cmsTagPluginChunkType* TagPluginChunk = ( _cmsTagPluginChunkType*) _cmsContextGetClientChunk(ContextID, TagPlugin); for (pt = TagPluginChunk->Tag; pt != NULL; pt = pt ->Next) { if (sig == pt -> Signature) return &pt ->Descriptor; } for (pt = SupportedTags; pt != NULL; pt = pt ->Next) { if (sig == pt -> Signature) return &pt ->Descriptor; } return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4827_0
crossvul-cpp_data_bad_4541_0
/* pb_decode.c -- decode a protobuf using minimal resources * * 2011 Petteri Aimonen <jpa@kapsi.fi> */ /* Use the GCC warn_unused_result attribute to check that all return values * are propagated correctly. On other compilers and gcc before 3.4.0 just * ignore the annotation. */ #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) #define checkreturn #else #define checkreturn __attribute__((warn_unused_result)) #endif #include "pb.h" #include "pb_decode.h" #include "pb_common.h" /************************************** * Declarations internal to this file * **************************************/ typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn; static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size); static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension); static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type); static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn find_extension_field(pb_field_iter_t *iter); static void pb_field_set_to_default(pb_field_iter_t *iter); static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct); static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof); static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); static bool checkreturn pb_skip_varint(pb_istream_t *stream); static bool checkreturn pb_skip_string(pb_istream_t *stream); #ifdef PB_ENABLE_MALLOC static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size); static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter); static void pb_release_single_field(const pb_field_iter_t *iter); #endif #ifdef PB_WITHOUT_64BIT #define pb_int64_t int32_t #define pb_uint64_t uint32_t #else #define pb_int64_t int64_t #define pb_uint64_t uint64_t #endif /* --- Function pointers to field decoders --- * Order in the array must match pb_action_t LTYPE numbering. */ static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = { &pb_dec_bool, &pb_dec_varint, &pb_dec_uvarint, &pb_dec_svarint, &pb_dec_fixed32, &pb_dec_fixed64, &pb_dec_bytes, &pb_dec_string, &pb_dec_submessage, NULL, /* extensions */ &pb_dec_fixed_length_bytes }; /******************************* * pb_istream_t implementation * *******************************/ static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) { size_t i; const pb_byte_t *source = (const pb_byte_t*)stream->state; stream->state = (pb_byte_t*)stream->state + count; if (buf != NULL) { for (i = 0; i < count; i++) buf[i] = source[i]; } return true; } bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) { if (count == 0) return true; #ifndef PB_BUFFER_ONLY if (buf == NULL && stream->callback != buf_read) { /* Skip input bytes */ pb_byte_t tmp[16]; while (count > 16) { if (!pb_read(stream, tmp, 16)) return false; count -= 16; } return pb_read(stream, tmp, count); } #endif if (stream->bytes_left < count) PB_RETURN_ERROR(stream, "end-of-stream"); #ifndef PB_BUFFER_ONLY if (!stream->callback(stream, buf, count)) PB_RETURN_ERROR(stream, "io error"); #else if (!buf_read(stream, buf, count)) return false; #endif stream->bytes_left -= count; return true; } /* Read a single byte from input stream. buf may not be NULL. * This is an optimization for the varint decoding. */ static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf) { if (stream->bytes_left == 0) PB_RETURN_ERROR(stream, "end-of-stream"); #ifndef PB_BUFFER_ONLY if (!stream->callback(stream, buf, 1)) PB_RETURN_ERROR(stream, "io error"); #else *buf = *(const pb_byte_t*)stream->state; stream->state = (pb_byte_t*)stream->state + 1; #endif stream->bytes_left--; return true; } pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize) { pb_istream_t stream; /* Cast away the const from buf without a compiler error. We are * careful to use it only in a const manner in the callbacks. */ union { void *state; const void *c_state; } state; #ifdef PB_BUFFER_ONLY stream.callback = NULL; #else stream.callback = &buf_read; #endif state.c_state = buf; stream.state = state.state; stream.bytes_left = bufsize; #ifndef PB_NO_ERRMSG stream.errmsg = NULL; #endif return stream; } /******************** * Helper functions * ********************/ static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof) { pb_byte_t byte; uint32_t result; if (!pb_readbyte(stream, &byte)) { if (stream->bytes_left == 0) { if (eof) { *eof = true; } } return false; } if ((byte & 0x80) == 0) { /* Quick case, 1 byte value */ result = byte; } else { /* Multibyte case */ uint_fast8_t bitpos = 7; result = byte & 0x7F; do { if (!pb_readbyte(stream, &byte)) return false; if (bitpos >= 32) { /* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */ uint8_t sign_extension = (bitpos < 63) ? 0xFF : 0x01; if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension)) { PB_RETURN_ERROR(stream, "varint overflow"); } } else { result |= (uint32_t)(byte & 0x7F) << bitpos; } bitpos = (uint_fast8_t)(bitpos + 7); } while (byte & 0x80); if (bitpos == 35 && (byte & 0x70) != 0) { /* The last byte was at bitpos=28, so only bottom 4 bits fit. */ PB_RETURN_ERROR(stream, "varint overflow"); } } *dest = result; return true; } bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest) { return pb_decode_varint32_eof(stream, dest, NULL); } #ifndef PB_WITHOUT_64BIT bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest) { pb_byte_t byte; uint_fast8_t bitpos = 0; uint64_t result = 0; do { if (bitpos >= 64) PB_RETURN_ERROR(stream, "varint overflow"); if (!pb_readbyte(stream, &byte)) return false; result |= (uint64_t)(byte & 0x7F) << bitpos; bitpos = (uint_fast8_t)(bitpos + 7); } while (byte & 0x80); *dest = result; return true; } #endif bool checkreturn pb_skip_varint(pb_istream_t *stream) { pb_byte_t byte; do { if (!pb_read(stream, &byte, 1)) return false; } while (byte & 0x80); return true; } bool checkreturn pb_skip_string(pb_istream_t *stream) { uint32_t length; if (!pb_decode_varint32(stream, &length)) return false; return pb_read(stream, NULL, length); } bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof) { uint32_t temp; *eof = false; *wire_type = (pb_wire_type_t) 0; *tag = 0; if (!pb_decode_varint32_eof(stream, &temp, eof)) { return false; } if (temp == 0) { *eof = true; /* Special feature: allow 0-terminated messages. */ return false; } *tag = temp >> 3; *wire_type = (pb_wire_type_t)(temp & 7); return true; } bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type) { switch (wire_type) { case PB_WT_VARINT: return pb_skip_varint(stream); case PB_WT_64BIT: return pb_read(stream, NULL, 8); case PB_WT_STRING: return pb_skip_string(stream); case PB_WT_32BIT: return pb_read(stream, NULL, 4); default: PB_RETURN_ERROR(stream, "invalid wire_type"); } } /* Read a raw value to buffer, for the purpose of passing it to callback as * a substream. Size is maximum size on call, and actual size on return. */ static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size) { size_t max_size = *size; switch (wire_type) { case PB_WT_VARINT: *size = 0; do { (*size)++; if (*size > max_size) return false; if (!pb_read(stream, buf, 1)) return false; } while (*buf++ & 0x80); return true; case PB_WT_64BIT: *size = 8; return pb_read(stream, buf, 8); case PB_WT_32BIT: *size = 4; return pb_read(stream, buf, 4); case PB_WT_STRING: /* Calling read_raw_value with a PB_WT_STRING is an error. * Explicitly handle this case and fallthrough to default to avoid * compiler warnings. */ default: PB_RETURN_ERROR(stream, "invalid wire_type"); } } /* Decode string length from stream and return a substream with limited length. * Remember to close the substream using pb_close_string_substream(). */ bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream) { uint32_t size; if (!pb_decode_varint32(stream, &size)) return false; *substream = *stream; if (substream->bytes_left < size) PB_RETURN_ERROR(stream, "parent stream too short"); substream->bytes_left = size; stream->bytes_left -= size; return true; } bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream) { if (substream->bytes_left) { if (!pb_read(substream, NULL, substream->bytes_left)) return false; } stream->state = substream->state; #ifndef PB_NO_ERRMSG stream->errmsg = substream->errmsg; #endif return true; } /************************* * Decode a single field * *************************/ static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_type_t type; pb_decoder_t func; type = iter->pos->type; func = PB_DECODERS[PB_LTYPE(type)]; switch (PB_HTYPE(type)) { case PB_HTYPE_REQUIRED: return func(stream, iter->pos, iter->pData); case PB_HTYPE_OPTIONAL: if (iter->pSize != iter->pData) *(bool*)iter->pSize = true; return func(stream, iter->pos, iter->pData); case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array */ bool status = true; pb_size_t *size = (pb_size_t*)iter->pSize; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left > 0 && *size < iter->pos->array_size) { void *pItem = (char*)iter->pData + iter->pos->data_size * (*size); if (!func(&substream, iter->pos, pItem)) { status = false; break; } (*size)++; } if (substream.bytes_left != 0) PB_RETURN_ERROR(stream, "array overflow"); if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Repeated field */ pb_size_t *size = (pb_size_t*)iter->pSize; char *pItem = (char*)iter->pData + iter->pos->data_size * (*size); if ((*size)++ >= iter->pos->array_size) PB_RETURN_ERROR(stream, "array overflow"); return func(stream, iter->pos, pItem); } case PB_HTYPE_ONEOF: *(pb_size_t*)iter->pSize = iter->pos->tag; if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) { /* We memset to zero so that any callbacks are set to NULL. * Then set any default values. */ memset(iter->pData, 0, iter->pos->data_size); pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData); } return func(stream, iter->pos, iter->pData); default: PB_RETURN_ERROR(stream, "invalid field type"); } } #ifdef PB_ENABLE_MALLOC /* Allocate storage for the field and store the pointer at iter->pData. * array_size is the number of entries to reserve in an array. * Zero size is not allowed, use pb_free() for releasing. */ static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size) { void *ptr = *(void**)pData; if (data_size == 0 || array_size == 0) PB_RETURN_ERROR(stream, "invalid size"); #ifdef __AVR__ /* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284 * Realloc to size of 1 byte can cause corruption of the malloc structures. */ if (data_size == 1 && array_size == 1) { data_size = 2; } #endif /* Check for multiplication overflows. * This code avoids the costly division if the sizes are small enough. * Multiplication is safe as long as only half of bits are set * in either multiplicand. */ { const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4); if (data_size >= check_limit || array_size >= check_limit) { const size_t size_max = (size_t)-1; if (size_max / array_size < data_size) { PB_RETURN_ERROR(stream, "size too large"); } } } /* Allocate new or expand previous allocation */ /* Note: on failure the old pointer will remain in the structure, * the message must be freed by caller also on error return. */ ptr = pb_realloc(ptr, array_size * data_size); if (ptr == NULL) PB_RETURN_ERROR(stream, "realloc failed"); *(void**)pData = ptr; return true; } /* Clear a newly allocated item in case it contains a pointer, or is a submessage. */ static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter) { if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING || PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES) { *(void**)pItem = NULL; } else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) { /* We memset to zero so that any callbacks are set to NULL. * Then set any default values. */ memset(pItem, 0, iter->pos->data_size); pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem); } } #endif static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { #ifndef PB_ENABLE_MALLOC PB_UNUSED(wire_type); PB_UNUSED(iter); PB_RETURN_ERROR(stream, "no malloc support"); #else pb_type_t type; pb_decoder_t func; type = iter->pos->type; func = PB_DECODERS[PB_LTYPE(type)]; switch (PB_HTYPE(type)) { case PB_HTYPE_REQUIRED: case PB_HTYPE_OPTIONAL: case PB_HTYPE_ONEOF: if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && *(void**)iter->pData != NULL) { /* Duplicate field, have to release the old allocation first. */ pb_release_single_field(iter); } if (PB_HTYPE(type) == PB_HTYPE_ONEOF) { *(pb_size_t*)iter->pSize = iter->pos->tag; } if (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES) { return func(stream, iter->pos, iter->pData); } else { if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1)) return false; initialize_pointer_field(*(void**)iter->pData, iter); return func(stream, iter->pos, *(void**)iter->pData); } case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array, multiple items come in at once. */ bool status = true; pb_size_t *size = (pb_size_t*)iter->pSize; size_t allocated_size = *size; void *pItem; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left) { if ((size_t)*size + 1 > allocated_size) { /* Allocate more storage. This tries to guess the * number of remaining entries. Round the division * upwards. */ allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1; if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size)) { status = false; break; } } /* Decode the array entry */ pItem = *(char**)iter->pData + iter->pos->data_size * (*size); initialize_pointer_field(pItem, iter); if (!func(&substream, iter->pos, pItem)) { status = false; break; } if (*size == PB_SIZE_MAX) { #ifndef PB_NO_ERRMSG stream->errmsg = "too many array entries"; #endif status = false; break; } (*size)++; } if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Normal repeated field, i.e. only one item at a time. */ pb_size_t *size = (pb_size_t*)iter->pSize; void *pItem; if (*size == PB_SIZE_MAX) PB_RETURN_ERROR(stream, "too many array entries"); (*size)++; if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size)) return false; pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1); initialize_pointer_field(pItem, iter); return func(stream, iter->pos, pItem); } default: PB_RETURN_ERROR(stream, "invalid field type"); } #endif } static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_callback_t *pCallback = (pb_callback_t*)iter->pData; #ifdef PB_OLD_CALLBACK_STYLE void *arg; #else void **arg; #endif if (pCallback == NULL || pCallback->funcs.decode == NULL) return pb_skip_field(stream, wire_type); #ifdef PB_OLD_CALLBACK_STYLE arg = pCallback->arg; #else arg = &(pCallback->arg); #endif if (wire_type == PB_WT_STRING) { pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; do { if (!pCallback->funcs.decode(&substream, iter->pos, arg)) PB_RETURN_ERROR(stream, "callback failed"); } while (substream.bytes_left); if (!pb_close_string_substream(stream, &substream)) return false; return true; } else { /* Copy the single scalar value to stack. * This is required so that we can limit the stream length, * which in turn allows to use same callback for packed and * not-packed fields. */ pb_istream_t substream; pb_byte_t buffer[10]; size_t size = sizeof(buffer); if (!read_raw_value(stream, wire_type, buffer, &size)) return false; substream = pb_istream_from_buffer(buffer, size); return pCallback->funcs.decode(&substream, iter->pos, arg); } } static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) { #ifdef PB_ENABLE_MALLOC /* When decoding an oneof field, check if there is old data that must be * released first. */ if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF) { if (!pb_release_union_field(stream, iter)) return false; } #endif switch (PB_ATYPE(iter->pos->type)) { case PB_ATYPE_STATIC: return decode_static_field(stream, wire_type, iter); case PB_ATYPE_POINTER: return decode_pointer_field(stream, wire_type, iter); case PB_ATYPE_CALLBACK: return decode_callback_field(stream, wire_type, iter); default: PB_RETURN_ERROR(stream, "invalid field type"); } } static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension) { /* Fake a field iterator for the extension field. * It is not actually safe to advance this iterator, but decode_field * will not even try to. */ const pb_field_t *field = (const pb_field_t*)extension->type->arg; (void)pb_field_iter_begin(iter, field, extension->dest); iter->pData = extension->dest; iter->pSize = &extension->found; if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { /* For pointer extensions, the pointer is stored directly * in the extension structure. This avoids having an extra * indirection. */ iter->pData = &extension->dest; } } /* Default handler for extension fields. Expects a pb_field_t structure * in extension->type->arg. */ static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type) { const pb_field_t *field = (const pb_field_t*)extension->type->arg; pb_field_iter_t iter; if (field->tag != tag) return true; iter_from_extension(&iter, extension); extension->found = true; return decode_field(stream, wire_type, &iter); } /* Try to decode an unknown field as an extension field. Tries each extension * decoder in turn, until one of them handles the field or loop ends. */ static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_extension_t *extension = *(pb_extension_t* const *)iter->pData; size_t pos = stream->bytes_left; while (extension != NULL && pos == stream->bytes_left) { bool status; if (extension->type->decode) status = extension->type->decode(stream, extension, tag, wire_type); else status = default_extension_decoder(stream, extension, tag, wire_type); if (!status) return false; extension = extension->next; } return true; } /* Step through the iterator until an extension field is found or until all * entries have been checked. There can be only one extension field per * message. Returns false if no extension field is found. */ static bool checkreturn find_extension_field(pb_field_iter_t *iter) { const pb_field_t *start = iter->pos; do { if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION) return true; (void)pb_field_iter_next(iter); } while (iter->pos != start); return false; } /* Initialize message fields to default values, recursively */ static void pb_field_set_to_default(pb_field_iter_t *iter) { pb_type_t type; type = iter->pos->type; if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) { pb_extension_t *ext = *(pb_extension_t* const *)iter->pData; while (ext != NULL) { pb_field_iter_t ext_iter; ext->found = false; iter_from_extension(&ext_iter, ext); pb_field_set_to_default(&ext_iter); ext = ext->next; } } else if (PB_ATYPE(type) == PB_ATYPE_STATIC) { bool init_data = true; if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData) { /* Set has_field to false. Still initialize the optional field * itself also. */ *(bool*)iter->pSize = false; } else if (PB_HTYPE(type) == PB_HTYPE_REPEATED || PB_HTYPE(type) == PB_HTYPE_ONEOF) { /* REPEATED: Set array count to 0, no need to initialize contents. ONEOF: Set which_field to 0. */ *(pb_size_t*)iter->pSize = 0; init_data = false; } if (init_data) { if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) { /* Initialize submessage to defaults */ pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData); } else if (iter->pos->ptr != NULL) { /* Initialize to default value */ memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size); } else { /* Initialize to zeros */ memset(iter->pData, 0, iter->pos->data_size); } } } else if (PB_ATYPE(type) == PB_ATYPE_POINTER) { /* Initialize the pointer to NULL. */ *(void**)iter->pData = NULL; /* Initialize array count to 0. */ if (PB_HTYPE(type) == PB_HTYPE_REPEATED || PB_HTYPE(type) == PB_HTYPE_ONEOF) { *(pb_size_t*)iter->pSize = 0; } } else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK) { /* Don't overwrite callback */ } } static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct) { pb_field_iter_t iter; if (!pb_field_iter_begin(&iter, fields, dest_struct)) return; /* Empty message type */ do { pb_field_set_to_default(&iter); } while (pb_field_iter_next(&iter)); } /********************* * Decode all fields * *********************/ bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0}; const uint32_t allbits = ~(uint32_t)0; uint32_t extension_range_start = 0; pb_field_iter_t iter; /* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed * count field. This can only handle _one_ repeated fixed count field that * is unpacked and unordered among other (non repeated fixed count) fields. */ const pb_field_t *fixed_count_field = NULL; pb_size_t fixed_count_size = 0; /* Return value ignored, as empty message types will be correctly handled by * pb_field_iter_find() anyway. */ (void)pb_field_iter_begin(&iter, fields, dest_struct); while (stream->bytes_left) { uint32_t tag; pb_wire_type_t wire_type; bool eof; if (!pb_decode_tag(stream, &wire_type, &tag, &eof)) { if (eof) break; else return false; } if (!pb_field_iter_find(&iter, tag)) { /* No match found, check if it matches an extension. */ if (tag >= extension_range_start) { if (!find_extension_field(&iter)) extension_range_start = (uint32_t)-1; else extension_range_start = iter.pos->tag; if (tag >= extension_range_start) { size_t pos = stream->bytes_left; if (!decode_extension(stream, tag, wire_type, &iter)) return false; if (pos != stream->bytes_left) { /* The field was handled */ continue; } } } /* No match found, skip data */ if (!pb_skip_field(stream, wire_type)) return false; continue; } /* If a repeated fixed count field was found, get size from * 'fixed_count_field' as there is no counter contained in the struct. */ if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED && iter.pSize == iter.pData) { if (fixed_count_field != iter.pos) { /* If the new fixed count field does not match the previous one, * check that the previous one is NULL or that it finished * receiving all the expected data. */ if (fixed_count_field != NULL && fixed_count_size != fixed_count_field->array_size) { PB_RETURN_ERROR(stream, "wrong size for fixed count field"); } fixed_count_field = iter.pos; fixed_count_size = 0; } iter.pSize = &fixed_count_size; } if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED && iter.required_field_index < PB_MAX_REQUIRED_FIELDS) { uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31)); fields_seen[iter.required_field_index >> 5] |= tmp; } if (!decode_field(stream, wire_type, &iter)) return false; } /* Check that all elements of the last decoded fixed count field were present. */ if (fixed_count_field != NULL && fixed_count_size != fixed_count_field->array_size) { PB_RETURN_ERROR(stream, "wrong size for fixed count field"); } /* Check that all required fields were present. */ { /* First figure out the number of required fields by * seeking to the end of the field array. Usually we * are already close to end after decoding. */ unsigned req_field_count; pb_type_t last_type; unsigned i; do { req_field_count = iter.required_field_index; last_type = iter.pos->type; } while (pb_field_iter_next(&iter)); /* Fixup if last field was also required. */ if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0) req_field_count++; if (req_field_count > PB_MAX_REQUIRED_FIELDS) req_field_count = PB_MAX_REQUIRED_FIELDS; if (req_field_count > 0) { /* Check the whole words */ for (i = 0; i < (req_field_count >> 5); i++) { if (fields_seen[i] != allbits) PB_RETURN_ERROR(stream, "missing required field"); } /* Check the remaining bits (if any) */ if ((req_field_count & 31) != 0) { if (fields_seen[req_field_count >> 5] != (allbits >> (32 - (req_field_count & 31)))) { PB_RETURN_ERROR(stream, "missing required field"); } } } } return true; } bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { bool status; pb_message_set_to_defaults(fields, dest_struct); status = pb_decode_noinit(stream, fields, dest_struct); #ifdef PB_ENABLE_MALLOC if (!status) pb_release(fields, dest_struct); #endif return status; } bool pb_decode_delimited_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { pb_istream_t substream; bool status; if (!pb_make_string_substream(stream, &substream)) return false; status = pb_decode_noinit(&substream, fields, dest_struct); if (!pb_close_string_substream(stream, &substream)) return false; return status; } bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { pb_istream_t substream; bool status; if (!pb_make_string_substream(stream, &substream)) return false; status = pb_decode(&substream, fields, dest_struct); if (!pb_close_string_substream(stream, &substream)) return false; return status; } bool pb_decode_nullterminated(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) { /* This behaviour will be separated in nanopb-0.4.0, see issue #278. */ return pb_decode(stream, fields, dest_struct); } #ifdef PB_ENABLE_MALLOC /* Given an oneof field, if there has already been a field inside this oneof, * release it before overwriting with a different one. */ static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter) { pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */ pb_size_t new_tag = iter->pos->tag; /* New which_ value */ if (old_tag == 0) return true; /* Ok, no old data in union */ if (old_tag == new_tag) return true; /* Ok, old data is of same type => merge */ /* Release old data. The find can fail if the message struct contains * invalid data. */ if (!pb_field_iter_find(iter, old_tag)) PB_RETURN_ERROR(stream, "invalid union tag"); pb_release_single_field(iter); /* Restore iterator to where it should be. * This shouldn't fail unless the pb_field_t structure is corrupted. */ if (!pb_field_iter_find(iter, new_tag)) PB_RETURN_ERROR(stream, "iterator error"); return true; } static void pb_release_single_field(const pb_field_iter_t *iter) { pb_type_t type; type = iter->pos->type; if (PB_HTYPE(type) == PB_HTYPE_ONEOF) { if (*(pb_size_t*)iter->pSize != iter->pos->tag) return; /* This is not the current field in the union */ } /* Release anything contained inside an extension or submsg. * This has to be done even if the submsg itself is statically * allocated. */ if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) { /* Release fields from all extensions in the linked list */ pb_extension_t *ext = *(pb_extension_t**)iter->pData; while (ext != NULL) { pb_field_iter_t ext_iter; iter_from_extension(&ext_iter, ext); pb_release_single_field(&ext_iter); ext = ext->next; } } else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && PB_ATYPE(type) != PB_ATYPE_CALLBACK) { /* Release fields in submessage or submsg array */ void *pItem = iter->pData; pb_size_t count = 1; if (PB_ATYPE(type) == PB_ATYPE_POINTER) { pItem = *(void**)iter->pData; } if (PB_HTYPE(type) == PB_HTYPE_REPEATED) { if (PB_ATYPE(type) == PB_ATYPE_STATIC && iter->pSize == iter->pData) { /* No _count field so use size of the array */ count = iter->pos->array_size; } else { count = *(pb_size_t*)iter->pSize; } if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size) { /* Protect against corrupted _count fields */ count = iter->pos->array_size; } } if (pItem) { while (count--) { pb_release((const pb_field_t*)iter->pos->ptr, pItem); pItem = (char*)pItem + iter->pos->data_size; } } } if (PB_ATYPE(type) == PB_ATYPE_POINTER) { if (PB_HTYPE(type) == PB_HTYPE_REPEATED && (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES)) { /* Release entries in repeated string or bytes array */ void **pItem = *(void***)iter->pData; pb_size_t count = *(pb_size_t*)iter->pSize; while (count--) { pb_free(*pItem); *pItem++ = NULL; } } if (PB_HTYPE(type) == PB_HTYPE_REPEATED) { /* We are going to release the array, so set the size to 0 */ *(pb_size_t*)iter->pSize = 0; } /* Release main item */ pb_free(*(void**)iter->pData); *(void**)iter->pData = NULL; } } void pb_release(const pb_field_t fields[], void *dest_struct) { pb_field_iter_t iter; if (!dest_struct) return; /* Ignore NULL pointers, similar to free() */ if (!pb_field_iter_begin(&iter, fields, dest_struct)) return; /* Empty message type */ do { pb_release_single_field(&iter); } while (pb_field_iter_next(&iter)); } #endif /* Field decoders */ bool pb_decode_bool(pb_istream_t *stream, bool *dest) { return pb_dec_bool(stream, NULL, (void*)dest); } bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest) { pb_uint64_t value; if (!pb_decode_varint(stream, &value)) return false; if (value & 1) *dest = (pb_int64_t)(~(value >> 1)); else *dest = (pb_int64_t)(value >> 1); return true; } bool pb_decode_fixed32(pb_istream_t *stream, void *dest) { pb_byte_t bytes[4]; if (!pb_read(stream, bytes, 4)) return false; *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) | ((uint32_t)bytes[1] << 8) | ((uint32_t)bytes[2] << 16) | ((uint32_t)bytes[3] << 24); return true; } #ifndef PB_WITHOUT_64BIT bool pb_decode_fixed64(pb_istream_t *stream, void *dest) { pb_byte_t bytes[8]; if (!pb_read(stream, bytes, 8)) return false; *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) | ((uint64_t)bytes[1] << 8) | ((uint64_t)bytes[2] << 16) | ((uint64_t)bytes[3] << 24) | ((uint64_t)bytes[4] << 32) | ((uint64_t)bytes[5] << 40) | ((uint64_t)bytes[6] << 48) | ((uint64_t)bytes[7] << 56); return true; } #endif static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t value; PB_UNUSED(field); if (!pb_decode_varint32(stream, &value)) return false; *(bool*)dest = (value != 0); return true; } static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest) { pb_uint64_t value; pb_int64_t svalue; pb_int64_t clamped; if (!pb_decode_varint(stream, &value)) return false; /* See issue 97: Google's C++ protobuf allows negative varint values to * be cast as int32_t, instead of the int64_t that should be used when * encoding. Previous nanopb versions had a bug in encoding. In order to * not break decoding of such messages, we cast <=32 bit fields to * int32_t first to get the sign correct. */ if (field->data_size == sizeof(pb_int64_t)) svalue = (pb_int64_t)value; else svalue = (int32_t)value; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_int64_t)) clamped = *(pb_int64_t*)dest = svalue; else if (field->data_size == sizeof(int32_t)) clamped = *(int32_t*)dest = (int32_t)svalue; else if (field->data_size == sizeof(int_least16_t)) clamped = *(int_least16_t*)dest = (int_least16_t)svalue; else if (field->data_size == sizeof(int_least8_t)) clamped = *(int_least8_t*)dest = (int_least8_t)svalue; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != svalue) PB_RETURN_ERROR(stream, "integer too large"); return true; } static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest) { pb_uint64_t value, clamped; if (!pb_decode_varint(stream, &value)) return false; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_uint64_t)) clamped = *(pb_uint64_t*)dest = value; else if (field->data_size == sizeof(uint32_t)) clamped = *(uint32_t*)dest = (uint32_t)value; else if (field->data_size == sizeof(uint_least16_t)) clamped = *(uint_least16_t*)dest = (uint_least16_t)value; else if (field->data_size == sizeof(uint_least8_t)) clamped = *(uint_least8_t*)dest = (uint_least8_t)value; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != value) PB_RETURN_ERROR(stream, "integer too large"); return true; } static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest) { pb_int64_t value, clamped; if (!pb_decode_svarint(stream, &value)) return false; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_int64_t)) clamped = *(pb_int64_t*)dest = value; else if (field->data_size == sizeof(int32_t)) clamped = *(int32_t*)dest = (int32_t)value; else if (field->data_size == sizeof(int_least16_t)) clamped = *(int_least16_t*)dest = (int_least16_t)value; else if (field->data_size == sizeof(int_least8_t)) clamped = *(int_least8_t*)dest = (int_least8_t)value; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != value) PB_RETURN_ERROR(stream, "integer too large"); return true; } static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest) { PB_UNUSED(field); return pb_decode_fixed32(stream, dest); } static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest) { PB_UNUSED(field); #ifndef PB_WITHOUT_64BIT return pb_decode_fixed64(stream, dest); #else PB_UNUSED(dest); PB_RETURN_ERROR(stream, "no 64bit support"); #endif } static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t size; size_t alloc_size; pb_bytes_array_t *bdest; if (!pb_decode_varint32(stream, &size)) return false; if (size > PB_SIZE_MAX) PB_RETURN_ERROR(stream, "bytes overflow"); alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size); if (size > alloc_size) PB_RETURN_ERROR(stream, "size too large"); if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { #ifndef PB_ENABLE_MALLOC PB_RETURN_ERROR(stream, "no malloc support"); #else if (!allocate_field(stream, dest, alloc_size, 1)) return false; bdest = *(pb_bytes_array_t**)dest; #endif } else { if (alloc_size > field->data_size) PB_RETURN_ERROR(stream, "bytes overflow"); bdest = (pb_bytes_array_t*)dest; } bdest->size = (pb_size_t)size; return pb_read(stream, bdest->bytes, size); } static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t size; size_t alloc_size; bool status; if (!pb_decode_varint32(stream, &size)) return false; /* Space for null terminator */ alloc_size = size + 1; if (alloc_size < size) PB_RETURN_ERROR(stream, "size too large"); if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { #ifndef PB_ENABLE_MALLOC PB_RETURN_ERROR(stream, "no malloc support"); #else if (!allocate_field(stream, dest, alloc_size, 1)) return false; dest = *(void**)dest; #endif } else { if (alloc_size > field->data_size) PB_RETURN_ERROR(stream, "string overflow"); } status = pb_read(stream, (pb_byte_t*)dest, size); *((pb_byte_t*)dest + size) = 0; return status; } static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest) { bool status; pb_istream_t substream; const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr; if (!pb_make_string_substream(stream, &substream)) return false; if (field->ptr == NULL) PB_RETURN_ERROR(stream, "invalid field descriptor"); /* New array entries need to be initialized, while required and optional * submessages have already been initialized in the top-level pb_decode. */ if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED) status = pb_decode(&substream, submsg_fields, dest); else status = pb_decode_noinit(&substream, submsg_fields, dest); if (!pb_close_string_substream(stream, &substream)) return false; return status; } static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) { uint32_t size; if (!pb_decode_varint32(stream, &size)) return false; if (size > PB_SIZE_MAX) PB_RETURN_ERROR(stream, "bytes overflow"); if (size == 0) { /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */ memset(dest, 0, field->data_size); return true; } if (size != field->data_size) PB_RETURN_ERROR(stream, "incorrect fixed length bytes size"); return pb_read(stream, (pb_byte_t*)dest, field->data_size); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4541_0
crossvul-cpp_data_good_351_13
/* * card-setcos.c: Support for PKI cards by Setec * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005 Antti Tapaninen <aet@cc.hut.fi> * Copyright (C) 2005 Zetes * * 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 "asn1.h" #include "cardctl.h" #define _FINEID_BROKEN_SELECT_FLAG 1 static struct sc_atr_table setcos_atrs[] = { /* some Nokia branded SC */ { "3B:1F:11:00:67:80:42:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_GENERIC, 0, NULL }, /* RSA SecurID 3100 */ { "3B:9F:94:40:1E:00:67:16:43:46:49:53:45:10:52:66:FF:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_PKI, 0, NULL }, /* FINEID 1016 (SetCOS 4.3.1B3/PKCS#15, VRK) */ { "3b:9f:94:40:1e:00:67:00:43:46:49:53:45:10:52:66:ff:81:90:00", "ff:ff:ff:ff:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID, SC_CARD_FLAG_RNG, NULL }, /* FINEID 2032 (EIDApplet/7816-15, VRK test) */ { "3b:6b:00:ff:80:62:00:a2:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:00:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2132 (EIDApplet/7816-15, 3rdparty test) */ { "3b:64:00:ff:80:62:00:a2", "ff:ff:00:ff:ff:ff:00:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2064 (EIDApplet/7816-15, VRK) */ { "3b:7b:00:00:00:80:62:00:51:56:46:69:6e:45:49:44", "ff:ff:00:ff:ff:ff:ff:f0:ff:ff:ff:ff:ff:ff:ff:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2164 (EIDApplet/7816-15, 3rdparty) */ { "3b:64:00:00:80:62:00:51", "ff:ff:ff:ff:ff:ff:f0:ff", NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID 2264 (EIDApplet/7816-15, OPK/EMV/AVANT) */ { "3b:6e:00:00:00:62:00:00:57:41:56:41:4e:54:10:81:90:00", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, { "3b:7b:94:00:00:80:62:11:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, 0, NULL }, /* FINEID cards 1.3.2011 with Samsung chips (round connector) that supports 2048 bit keys. */ { "3b:7b:94:00:00:80:62:12:51:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2_2048, 0, NULL }, /* FINEID card for organisations, chip unknown. */ { "3b:7b:18:00:00:80:62:01:54:56:46:69:6e:45:49:44", NULL, NULL, SC_CARD_TYPE_SETCOS_FINEID_V2, _FINEID_BROKEN_SELECT_FLAG, NULL }, /* Swedish NIDEL card */ { "3b:9f:94:80:1f:c3:00:68:10:44:05:01:46:49:53:45:31:c8:07:90:00:18", NULL, NULL, SC_CARD_TYPE_SETCOS_NIDEL, 0, NULL }, /* Setcos 4.4.1 */ { "3b:9f:94:80:1f:c3:00:68:11:44:05:01:46:49:53:45:31:c8:00:00:00:00", "ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:00:00:00:00", NULL, SC_CARD_TYPE_SETCOS_44, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define SETCOS_IS_EID_APPLET(card) ((card)->type == SC_CARD_TYPE_SETCOS_EID_V2_0 || (card)->type == SC_CARD_TYPE_SETCOS_EID_V2_1) /* Setcos 4.4 Life Cycle Status Integer */ #define SETEC_LCSI_CREATE 0x01 #define SETEC_LCSI_INIT 0x03 #define SETEC_LCSI_ACTIVATED 0x07 #define SETEC_LCSI_DEACTIVATE 0x06 #define SETEC_LCSI_TEMINATE 0x0F /* MF only */ static struct sc_card_operations setcos_ops; static struct sc_card_driver setcos_drv = { "Setec cards", "setcos", &setcos_ops, NULL, 0, NULL }; static int match_hist_bytes(sc_card_t *card, const char *str, size_t len) { const char *src = (const char *) card->reader->atr_info.hist_bytes; size_t srclen = card->reader->atr_info.hist_bytes_len; size_t offset = 0; if (len == 0) len = strlen(str); if (srclen < len) return 0; while (srclen - offset > len) { if (memcmp(src + offset, str, len) == 0) { return 1; } offset++; } return 0; } static int setcos_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 buf[6]; int i; i = _sc_match_atr(card, setcos_atrs, &card->type); if (i < 0) { /* Unknown card, but has the FinEID application for sure */ if (match_hist_bytes(card, "FinEID", 0)) { card->type = SC_CARD_TYPE_SETCOS_FINEID_V2_2048; return 1; } if (match_hist_bytes(card, "FISE", 0)) { card->type = SC_CARD_TYPE_SETCOS_GENERIC; return 1; } /* Check if it's a EID2.x applet by reading the version info */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0xDF, 0x30); apdu.cla = 0x00; apdu.resp = buf; apdu.resplen = 5; apdu.le = 5; i = sc_transmit_apdu(card, &apdu); if (i == 0 && apdu.sw1 == 0x90 && apdu.sw2 == 0x00 && apdu.resplen == 5) { if (memcmp(buf, "v2.0", 4) == 0) card->type = SC_CARD_TYPE_SETCOS_EID_V2_0; else if (memcmp(buf, "v2.1", 4) == 0) card->type = SC_CARD_TYPE_SETCOS_EID_V2_1; else { buf[sizeof(buf) - 1] = '\0'; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "SetCOS EID applet %s is not supported", (char *) buf); return 0; } return 1; } return 0; } card->flags = setcos_atrs[i].flags; return 1; } static int select_pkcs15_app(sc_card_t * card) { sc_path_t app; int r; /* Regular PKCS#15 AID */ sc_format_path("A000000063504B43532D3135", &app); app.type = SC_PATH_TYPE_DF_NAME; r = sc_select_file(card, &app, NULL); return r; } static int setcos_init(sc_card_t *card) { card->name = "SetCOS"; /* Handle unknown or forced cards */ if (card->type < 0) { card->type = SC_CARD_TYPE_SETCOS_GENERIC; } switch (card->type) { case SC_CARD_TYPE_SETCOS_FINEID: case SC_CARD_TYPE_SETCOS_FINEID_V2_2048: case SC_CARD_TYPE_SETCOS_NIDEL: card->cla = 0x00; select_pkcs15_app(card); if (card->flags & SC_CARD_FLAG_RNG) card->caps |= SC_CARD_CAP_RNG; break; case SC_CARD_TYPE_SETCOS_44: case SC_CARD_TYPE_SETCOS_EID_V2_0: case SC_CARD_TYPE_SETCOS_EID_V2_1: card->cla = 0x00; card->caps |= SC_CARD_CAP_USE_FCI_AC; card->caps |= SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; break; default: /* XXX: Get SetCOS version */ card->cla = 0x80; /* SetCOS 4.3.x */ /* State that we have an RNG */ card->caps |= SC_CARD_CAP_RNG; break; } switch (card->type) { case SC_CARD_TYPE_SETCOS_PKI: case SC_CARD_TYPE_SETCOS_FINEID_V2_2048: { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } break; case SC_CARD_TYPE_SETCOS_44: case SC_CARD_TYPE_SETCOS_NIDEL: case SC_CARD_TYPE_SETCOS_EID_V2_0: case SC_CARD_TYPE_SETCOS_EID_V2_1: { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_HASH_SHA1; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _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); } break; } return 0; } static const struct sc_card_operations *iso_ops = NULL; static int setcos_construct_fci_44(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; const u8 *pin_key_info; int len; /* Command */ *p++ = 0x6F; p++; /* Size (set to 0 for keys/PINs on a Java card) */ if (SETCOS_IS_EID_APPLET(card) && (file->type == SC_FILE_TYPE_INTERNAL_EF || (file->type == SC_FILE_TYPE_WORKING_EF && file->ef_structure == 0x22))) buf[0] = buf[1] = 0x00; else { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; } sc_asn1_put_tag(0x81, buf, 2, p, *outlen - (p - out), &p); /* Type */ if (file->type_attr_len) { memcpy(buf, file->type_attr, file->type_attr_len); sc_asn1_put_tag(0x82, buf, file->type_attr_len, p, *outlen - (p - out), &p); } else { u8 bLen = 1; buf[0] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_INTERNAL_EF: /* RSA keyfile */ buf[0] = 0x11; break; case SC_FILE_TYPE_WORKING_EF: if (file->ef_structure == 0x22) { /* pin-file */ buf[0] = 0x0A; /* EF linear fixed EF for ISF keys */ if (SETCOS_IS_EID_APPLET(card)) bLen = 1; else { /* Setcos V4.4 */ bLen = 5; buf[1] = 0x41; /* fixed */ buf[2] = file->record_length >> 8; /* 2 byte record length */ buf[3] = file->record_length & 0xFF; buf[4] = file->size / file->record_length; /* record count */ } } else { buf[0] |= file->ef_structure & 7; /* set file-type, only for EF, not for DF objects */ } break; case SC_FILE_TYPE_DF: buf[0] = 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, bLen, p, *outlen - (p - out), &p); } /* File ID */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); /* DF name */ if (file->type == SC_FILE_TYPE_DF) { if (file->name[0] != 0) sc_asn1_put_tag(0x84, (u8 *) file->name, file->namelen, p, *outlen - (p - out), &p); else { /* Name required -> take the FID if not specified */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x84, buf, 2, p, *outlen - (p - out), &p); } } /* Security Attributes */ memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); /* Life cycle status */ if (file->prop_attr_len) { memcpy(buf, file->prop_attr, file->prop_attr_len); sc_asn1_put_tag(0x8A, buf, file->prop_attr_len, p, *outlen - (p - out), &p); } /* PIN definitions */ if (file->type == SC_FILE_TYPE_DF) { if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_1) { pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84"; len = 6; } else if (card->type == SC_CARD_TYPE_SETCOS_EID_V2_0) { pin_key_info = (const u8*)"\xC1\x04\x81\x82"; /* Max 2 PINs supported */ len = 4; } else { /* Pin/key info: define 4 pins, no keys */ if(file->path.len == 2) pin_key_info = (const u8*)"\xC1\x04\x81\x82\x83\x84\xC2\x00"; /* root-MF: use local pin-file */ else pin_key_info = (const u8 *)"\xC1\x04\x01\x02\x03\x04\xC2\x00"; /* sub-DF: use parent pin-file in root-MF */ len = 8; } sc_asn1_put_tag(0xA5, pin_key_info, len, p, *outlen - (p - out), &p); } /* Length */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int setcos_construct_fci(sc_card_t *card, const sc_file_t *file, u8 *out, size_t *outlen) { if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) return setcos_construct_fci_44(card, file, out, outlen); else return iso_ops->construct_fci(card, file, out, outlen); } static u8 acl_to_byte(const sc_acl_entry_t *e) { switch (e->method) { case SC_AC_NONE: return 0x00; case SC_AC_CHV: switch (e->key_ref) { case 1: return 0x01; break; case 2: return 0x02; break; default: return 0x00; } break; case SC_AC_TERM: return 0x04; case SC_AC_NEVER: return 0x0F; } return 0x00; } static unsigned int acl_to_byte_44(const struct sc_acl_entry *e, u8* p_bNumber) { /* Handle special fixed values */ if (e == (sc_acl_entry_t *) 1) /* SC_AC_NEVER */ return SC_AC_NEVER; else if ((e == (sc_acl_entry_t *) 2) || /* SC_AC_NONE */ (e == (sc_acl_entry_t *) 3) || /* SC_AC_UNKNOWN */ (e == (sc_acl_entry_t *) 0)) return SC_AC_NONE; /* Handle standard values */ *p_bNumber = e->key_ref; return(e->method); } /* If pin is present in the pins list, return it's index. * If it's not yet present, add it to the list and return the index. */ static int setcos_pin_index_44(int *pins, int len, int pin) { int i; for (i = 0; i < len; i++) { if (pins[i] == pin) return i; if (pins[i] == -1) { pins[i] = pin; return i; } } assert(i != len); /* Too much PINs, shouldn't happen */ return 0; } /* The ACs are always for the SETEC_LCSI_ACTIVATED state, even if * we have to create the file in the SC_FILE_STATUS_INITIALISATION state. */ static int setcos_create_file_44(sc_card_t *card, sc_file_t *file) { const u8 bFileStatus = file->status == SC_FILE_STATUS_CREATION ? SETEC_LCSI_CREATE : SETEC_LCSI_ACTIVATED; u8 bCommands_always = 0; int pins[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; u8 bCommands_pin[sizeof(pins)/sizeof(pins[0])]; /* both 7 entries big */ u8 bCommands_key = 0; u8 bNumber = 0; u8 bKeyNumber = 0; unsigned int bMethod = 0; /* -1 means RFU */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { /* note: SC_AC_OP_SELECT to be ignored, actually RFU */ SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; /* Set file creation status */ sc_file_set_prop_attr(file, &bFileStatus, 1); /* Build ACI from local structure = get AC for each operation group */ if (file->sec_attr_len == 0) { const int* p_idx; int i; int len = 0; u8 bBuf[64]; /* Get specific operation groups for specified file-type */ switch (file->type){ case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* SC_FILE_TYPE_WORKING_EF */ p_idx = ef_idx; break; } /* Get enabled commands + required Keys/Pins */ memset(bCommands_pin, 0, sizeof(bCommands_pin)); for (i = 7; i >= 0; i--) { /* for each AC Setcos operation */ bCommands_always <<= 1; bCommands_key <<= 1; if (p_idx[i] == -1) /* -1 means that bit is RFU -> set to 0 */ continue; bMethod = acl_to_byte_44(file->acl[ p_idx[i] ], &bNumber); /* Convert to OpenSc-index, convert to pin/key number */ switch(bMethod){ case SC_AC_NONE: /* always allowed */ bCommands_always |= 1; break; case SC_AC_CHV: /* pin */ if ((bNumber & 0x7F) == 0 || (bNumber & 0x7F) > 7) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "SetCOS 4.4 PIN refs can only be 1..7\n"); return SC_ERROR_INVALID_ARGUMENTS; } bCommands_pin[setcos_pin_index_44(pins, sizeof(pins), (int) bNumber)] |= 1 << i; break; case SC_AC_TERM: /* key */ bKeyNumber = bNumber; /* There should be only 1 key */ bCommands_key |= 1; break; } } /* Add the commands that are always allowed */ if (bCommands_always) { bBuf[len++] = 1; bBuf[len++] = bCommands_always; } /* Add commands that require pins */ for (i = 0; i < (int)sizeof(bCommands_pin) && pins[i] != -1; i++) { bBuf[len++] = 2; bBuf[len++] = bCommands_pin[i]; if (SETCOS_IS_EID_APPLET(card)) bBuf[len++] = pins[i]; /* pin ref */ else bBuf[len++] = pins[i] & 0x07; /* pin ref */ } /* Add commands that require the key */ if (bCommands_key) { bBuf[len++] = 2 | 0x20; /* indicate keyNumber present */ bBuf[len++] = bCommands_key; bBuf[len++] = bKeyNumber; } /* RSA signing/decryption requires AC adaptive coding, can't be put in AC simple coding. Only implemented for pins, not for a key. */ if ( (file->type == SC_FILE_TYPE_INTERNAL_EF) && (acl_to_byte_44(file->acl[SC_AC_OP_CRYPTO], &bNumber) == SC_AC_CHV) ) { bBuf[len++] = 0x83; bBuf[len++] = 0x01; bBuf[len++] = 0x2A; /* INS byte for the sign/decrypt APDU */ bBuf[len++] = bNumber & 0x07; /* pin ref */ } sc_file_set_sec_attr(file, bBuf, len); } return iso_ops->create_file(card, file); } static int setcos_create_file(sc_card_t *card, sc_file_t *file) { if (card->type == SC_CARD_TYPE_SETCOS_44 || SETCOS_IS_EID_APPLET(card)) return setcos_create_file_44(card, file); if (file->prop_attr_len == 0) sc_file_set_prop_attr(file, (const u8 *) "\x03\x00\x00", 3); if (file->sec_attr_len == 0) { int idx[6], i; u8 buf[6]; if (file->type == SC_FILE_TYPE_DF) { const int df_idx[6] = { SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = df_idx[i]; } else { const int ef_idx[6] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = ef_idx[i]; } for (i = 0; i < 6; i++) { const struct sc_acl_entry *entry; entry = sc_file_get_acl_entry(file, idx[i]); buf[i] = acl_to_byte(entry); } sc_file_set_sec_attr(file, buf, 6); } return iso_ops->create_file(card, file); } static int setcos_set_security_env2(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 *p; int r, locked = 0; assert(card != NULL && env != NULL); if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) { if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "symmetric keyref not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } if (se_num > 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "restore security environment not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0); switch (env->operation) { case SC_SEC_OPERATION_DECIPHER: /* Should be 0x81 */ apdu.p1 = 0x41; apdu.p2 = 0xB8; break; case SC_SEC_OPERATION_SIGN: /* Should be 0x41 */ apdu.p1 = ((card->type == SC_CARD_TYPE_SETCOS_FINEID_V2) || (card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048) || (card->type == SC_CARD_TYPE_SETCOS_44) || (card->type == SC_CARD_TYPE_SETCOS_NIDEL) || SETCOS_IS_EID_APPLET(card)) ? 0x41 : 0x81; apdu.p2 = 0xB6; break; default: return SC_ERROR_INVALID_ARGUMENTS; } apdu.le = 0; p = sbuf; if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = env->algorithm_ref & 0xFF; } if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) { *p++ = 0x81; *p++ = env->file_ref.len; memcpy(p, env->file_ref.value, env->file_ref.len); p += env->file_ref.len; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT && !(card->type == SC_CARD_TYPE_SETCOS_NIDEL || card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048)) { if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) *p++ = 0x83; else *p++ = 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; apdu.resplen = 0; if (se_num > 0) { r = sc_lock(card); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu(card, &apdu); if (r) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%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(card, &apdu); sc_unlock(card); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int setcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { if (env->flags & SC_SEC_ENV_ALG_PRESENT) { sc_security_env_t tmp; tmp = *env; tmp.flags &= ~SC_SEC_ENV_ALG_PRESENT; tmp.flags |= SC_SEC_ENV_ALG_REF_PRESENT; if (tmp.algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Only RSA algorithm supported.\n"); return SC_ERROR_NOT_SUPPORTED; } switch (card->type) { case SC_CARD_TYPE_SETCOS_PKI: case SC_CARD_TYPE_SETCOS_FINEID: case SC_CARD_TYPE_SETCOS_FINEID_V2_2048: case SC_CARD_TYPE_SETCOS_NIDEL: case SC_CARD_TYPE_SETCOS_44: case SC_CARD_TYPE_SETCOS_EID_V2_0: case SC_CARD_TYPE_SETCOS_EID_V2_1: break; default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card does not support RSA.\n"); return SC_ERROR_NOT_SUPPORTED; break; } tmp.algorithm_ref = 0x00; /* potential FIXME: return an error, if an unsupported * pad or hash was requested, although this shouldn't happen. */ if (env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1) tmp.algorithm_ref = 0x02; if (tmp.algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) tmp.algorithm_ref |= 0x10; return setcos_set_security_env2(card, &tmp, se_num); } return setcos_set_security_env2(card, env, se_num); } static void add_acl_entry(sc_file_t *file, int op, u8 byte) { unsigned int method, key_ref = SC_AC_KEY_REF_NONE; switch (byte >> 4) { case 0: method = SC_AC_NONE; break; case 1: method = SC_AC_CHV; key_ref = 1; break; case 2: method = SC_AC_CHV; key_ref = 2; break; case 4: method = SC_AC_TERM; break; case 15: method = SC_AC_NEVER; break; default: method = SC_AC_UNKNOWN; break; } sc_file_add_acl_entry(file, op, method, key_ref); } static void parse_sec_attr(sc_file_t *file, const u8 * buf, size_t len) { int i; int idx[6]; if (len < 6) return; if (file->type == SC_FILE_TYPE_DF) { const int df_idx[6] = { SC_AC_OP_SELECT, SC_AC_OP_LOCK, SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = df_idx[i]; } else { const int ef_idx[6] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_ERASE, SC_AC_OP_REHABILITATE, SC_AC_OP_INVALIDATE }; for (i = 0; i < 6; i++) idx[i] = ef_idx[i]; } for (i = 0; i < 6; i++) add_acl_entry(file, idx[i], buf[i]); } static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) { /* OpenSc Operation values for each command operation-type */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; u8 bValue; int i; int iKeyRef = 0; int iMethod; int iPinCount; int iOffset = 0; int iOperation; const int* p_idx; /* Check all sub-AC definitions within the total AC */ while (len > 1) { /* minimum length = 2 */ int iACLen = buf[iOffset] & 0x0F; if ((size_t) iACLen > len) break; iPinCount = -1; /* default no pin required */ iMethod = SC_AC_NONE; /* default no authentication required */ if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ int iParmLen = 1; /* command-byte is always present */ int iKeyLen = 0; /* Encryption key is optional */ if (buf[iOffset] & 0x20) iKeyLen++; if (buf[iOffset+1] & 0x40) iParmLen++; if (buf[iOffset+1] & 0x20) iParmLen++; if (buf[iOffset+1] & 0x10) iParmLen++; if (buf[iOffset+1] & 0x08) iParmLen++; /* Get KeyNumber if available */ if(iKeyLen) { int iSC; if (len < 1+iACLen) break; iSC = buf[iOffset+iACLen]; switch( (iSC>>5) & 0x03 ){ case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ } /* Get PinNumber if available */ if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ if (len < 1+1+1+iParmLen) break; iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ iMethod = SC_AC_CHV; } /* Convert SETCOS command to OpenSC command group */ if (len < 1+2) break; switch(buf[iOffset+2]){ case 0x2A: /* crypto operation */ iOperation = SC_AC_OP_CRYPTO; break; case 0x46: /* key-generation operation */ iOperation = SC_AC_OP_UPDATE; break; default: iOperation = SC_AC_OP_SELECT; break; } sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); } else { /* AC in simple coding */ /* Initial AC is treated as an operational AC */ /* Get specific Cmd groups for specified file-type */ switch (file->type) { case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* EF */ p_idx = ef_idx; break; } /* Encryption key present ? */ iPinCount = iACLen - 1; if (buf[iOffset] & 0x20) { int iSC; if (len < 1 + iACLen) break; iSC = buf[iOffset + iACLen]; switch( (iSC>>5) & 0x03 ) { case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ iPinCount--; /* one byte used for keyReference */ } /* Pin present ? */ if ( iPinCount > 0 ) { if (len < 1 + 2) break; iKeyRef = buf[iOffset + 2]; /* pin ref */ iMethod = SC_AC_CHV; } /* Add AC for each command-operationType into OpenSc structure */ bValue = buf[iOffset + 1]; for (i = 0; i < 8; i++) { if((bValue & 1) && (p_idx[i] >= 0)) sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); bValue >>= 1; } } /* Current field treated, get next AC sub-field */ iOffset += iACLen +1; /* AC + PTL-byte */ len -= iACLen +1; } } static int setcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file) { int r; r = iso_ops->select_file(card, in_path, file); /* Certain FINeID cards for organisations return 6A88 instead of 6A82 for missing files */ if (card->flags & _FINEID_BROKEN_SELECT_FLAG && r == SC_ERROR_DATA_OBJECT_NOT_FOUND) return SC_ERROR_FILE_NOT_FOUND; if (r) return r; if (file != NULL) { if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) parse_sec_attr_44(*file, (*file)->sec_attr, (*file)->sec_attr_len); else parse_sec_attr(*file, (*file)->sec_attr, (*file)->sec_attr_len); } return 0; } static int setcos_list_files(sc_card_t *card, u8 * buf, size_t buflen) { sc_apdu_t apdu; int r; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, 0, 0); if (card->type == SC_CARD_TYPE_SETCOS_44 || card->type == SC_CARD_TYPE_SETCOS_NIDEL || SETCOS_IS_EID_APPLET(card)) apdu.cla = 0x80; apdu.resp = buf; apdu.resplen = buflen; apdu.le = buflen > 256 ? 256 : buflen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (card->type == SC_CARD_TYPE_SETCOS_44 && apdu.sw1 == 0x6A && apdu.sw2 == 0x82) return 0; /* no files found */ if (apdu.resplen == 0) return sc_check_sw(card, apdu.sw1, apdu.sw2); return apdu.resplen; } static int setcos_process_fci(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t buflen) { int r = iso_ops->process_fci(card, file, buf, buflen); /* SetCOS 4.4: RSA key file is an internal EF but it's * file descriptor doesn't seem to follow ISO7816. */ if (r >= 0 && (card->type == SC_CARD_TYPE_SETCOS_44 || SETCOS_IS_EID_APPLET(card))) { const u8 *tag; size_t taglen = 1; tag = (u8 *) sc_asn1_find_tag(card->ctx, buf, buflen, 0x82, &taglen); if (tag != NULL && taglen == 1 && *tag == 0x11) file->type = SC_FILE_TYPE_INTERNAL_EF; } return r; } /* Write internal data, e.g. add default pin-records to pin-file */ static int setcos_putdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj) { int r; struct sc_apdu apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); memset(&apdu, 0, sizeof(apdu)); apdu.cse = SC_APDU_CASE_3_SHORT; apdu.cla = 0x00; apdu.ins = 0xDA; apdu.p1 = data_obj->P1; apdu.p2 = data_obj->P2; apdu.lc = data_obj->DataLen; apdu.datalen = data_obj->DataLen; apdu.data = data_obj->Data; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "PUT_DATA returned error"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* Read internal data, e.g. get RSA public key */ static int setcos_getdata(struct sc_card *card, struct sc_cardctl_setcos_data_obj* data_obj) { int r; struct sc_apdu apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); memset(&apdu, 0, sizeof(apdu)); apdu.cse = SC_APDU_CASE_2_SHORT; apdu.cla = 0x00; apdu.ins = 0xCA; /* GET DATA */ apdu.p1 = data_obj->P1; apdu.p2 = data_obj->P2; apdu.lc = 0; apdu.datalen = 0; apdu.data = data_obj->Data; apdu.le = 256; apdu.resp = data_obj->Data; apdu.resplen = data_obj->DataLen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "GET_DATA returned error"); if (apdu.resplen > data_obj->DataLen) r = SC_ERROR_WRONG_LENGTH; else data_obj->DataLen = apdu.resplen; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* Generate or store a key */ static int setcos_generate_store_key(sc_card_t *card, struct sc_cardctl_setcos_gen_store_key_info *data) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int r, len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Setup key-generation parameters */ len = 0; if (data->op_type == OP_TYPE_GENERATE) sbuf[len++] = 0x92; /* algo ID: RSA CRT */ else sbuf[len++] = 0x9A; /* algo ID: EXTERNALLY GENERATED RSA CRT */ sbuf[len++] = 0x00; sbuf[len++] = data->mod_len / 256; /* 2 bytes for modulus bitlength */ sbuf[len++] = data->mod_len % 256; sbuf[len++] = data->pubexp_len / 256; /* 2 bytes for pubexp bitlength */ sbuf[len++] = data->pubexp_len % 256; memcpy(sbuf + len, data->pubexp, (data->pubexp_len + 7) / 8); len += (data->pubexp_len + 7) / 8; if (data->op_type == OP_TYPE_STORE) { sbuf[len++] = data->primep_len / 256; sbuf[len++] = data->primep_len % 256; memcpy(sbuf + len, data->primep, (data->primep_len + 7) / 8); len += (data->primep_len + 7) / 8; sbuf[len++] = data->primeq_len / 256; sbuf[len++] = data->primeq_len % 256; memcpy(sbuf + len, data->primeq, (data->primeq_len + 7) / 8); len += (data->primeq_len + 7) / 8; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.cla = 0x00; apdu.data = sbuf; apdu.datalen = len; apdu.lc = len; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "STORE/GENERATE_KEY returned error"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int setcos_activate_file(sc_card_t *card) { int r; u8 sbuf[2]; sc_apdu_t apdu; sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x44, 0x00, 0x00); apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "ACTIVATE_FILE returned error"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int setcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { if (card->type != SC_CARD_TYPE_SETCOS_44 && !SETCOS_IS_EID_APPLET(card)) return SC_ERROR_NOT_SUPPORTED; switch(cmd) { case SC_CARDCTL_SETCOS_PUTDATA: return setcos_putdata(card, (struct sc_cardctl_setcos_data_obj*) ptr); break; case SC_CARDCTL_SETCOS_GETDATA: return setcos_getdata(card, (struct sc_cardctl_setcos_data_obj*) ptr); break; case SC_CARDCTL_SETCOS_GENERATE_STORE_KEY: return setcos_generate_store_key(card, (struct sc_cardctl_setcos_gen_store_key_info *) ptr); case SC_CARDCTL_SETCOS_ACTIVATE_FILE: return setcos_activate_file(card); } return SC_ERROR_NOT_SUPPORTED; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); setcos_ops = *iso_drv->ops; setcos_ops.match_card = setcos_match_card; setcos_ops.init = setcos_init; if (iso_ops == NULL) iso_ops = iso_drv->ops; setcos_ops.create_file = setcos_create_file; setcos_ops.set_security_env = setcos_set_security_env; setcos_ops.select_file = setcos_select_file; setcos_ops.list_files = setcos_list_files; setcos_ops.process_fci = setcos_process_fci; setcos_ops.construct_fci = setcos_construct_fci; setcos_ops.card_ctl = setcos_card_ctl; return &setcos_drv; } struct sc_card_driver *sc_get_setcos_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_13
crossvul-cpp_data_good_486_1
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Bitmap decompression routines Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008 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 3 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/>. */ /* three separate function for speed when decompressing the bitmaps when modifying one function make the change in the others jay.sorg@gmail.com */ /* indent is confused by this file */ /* *INDENT-OFF* */ #include "rdesktop.h" #define CVAL(p) (*(p++)) #ifdef NEED_ALIGN #ifdef L_ENDIAN #define CVAL2(p, v) { v = (*(p++)); v |= (*(p++)) << 8; } #else #define CVAL2(p, v) { v = (*(p++)) << 8; v |= (*(p++)); } #endif /* L_ENDIAN */ #else #define CVAL2(p, v) { v = (*((uint16*)p)); p += 2; } #endif /* NEED_ALIGN */ #define UNROLL8(exp) { exp exp exp exp exp exp exp exp } #define REPEAT(statement) \ { \ while((count & ~0x7) && ((x+8) < width)) \ UNROLL8( statement; count--; x++; ); \ \ while((count > 0) && (x < width)) \ { \ statement; \ count--; \ x++; \ } \ } #define MASK_UPDATE() \ { \ mixmask <<= 1; \ if (mixmask == 0) \ { \ mask = fom_mask ? fom_mask : CVAL(input); \ mixmask = 1; \ } \ } /* 1 byte bitmap decompress */ static RD_BOOL bitmap_decompress1(uint8 * output, int width, int height, uint8 * input, int size) { uint8 *end = input + size; uint8 *prevline = NULL, *line = NULL; int opcode, count, offset, isfillormix, x = width; int lastopcode = -1, insertmix = False, bicolour = False; uint8 code; uint8 colour1 = 0, colour2 = 0; uint8 mixmask, mask = 0; uint8 mix = 0xff; int fom_mask = 0; while (input < end) { fom_mask = 0; code = CVAL(input); opcode = code >> 4; /* Handle different opcode forms */ switch (opcode) { case 0xc: case 0xd: case 0xe: opcode -= 6; count = code & 0xf; offset = 16; break; case 0xf: opcode = code & 0xf; if (opcode < 9) { count = CVAL(input); count |= CVAL(input) << 8; } else { count = (opcode < 0xb) ? 8 : 1; } offset = 0; break; default: opcode >>= 1; count = code & 0x1f; offset = 32; break; } /* Handle strange cases for counts */ if (offset != 0) { isfillormix = ((opcode == 2) || (opcode == 7)); if (count == 0) { if (isfillormix) count = CVAL(input) + 1; else count = CVAL(input) + offset; } else if (isfillormix) { count <<= 3; } } /* Read preliminary data */ switch (opcode) { case 0: /* Fill */ if ((lastopcode == opcode) && !((x == width) && (prevline == NULL))) insertmix = True; break; case 8: /* Bicolour */ colour1 = CVAL(input); colour2 = CVAL(input); break; case 3: /* Colour */ colour2 = CVAL(input); break; case 6: /* SetMix/Mix */ case 7: /* SetMix/FillOrMix */ mix = CVAL(input); opcode -= 5; break; case 9: /* FillOrMix_1 */ mask = 0x03; opcode = 0x02; fom_mask = 3; break; case 0x0a: /* FillOrMix_2 */ mask = 0x05; opcode = 0x02; fom_mask = 5; break; } lastopcode = opcode; mixmask = 0; /* Output body */ while (count > 0) { if (x >= width) { if (height <= 0) return False; x = 0; height--; prevline = line; line = output + height * width; } switch (opcode) { case 0: /* Fill */ if (insertmix) { if (prevline == NULL) line[x] = mix; else line[x] = prevline[x] ^ mix; insertmix = False; count--; x++; } if (prevline == NULL) { REPEAT(line[x] = 0) } else { REPEAT(line[x] = prevline[x]) } break; case 1: /* Mix */ if (prevline == NULL) { REPEAT(line[x] = mix) } else { REPEAT(line[x] = prevline[x] ^ mix) } break; case 2: /* Fill or Mix */ if (prevline == NULL) { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = mix; else line[x] = 0; ) } else { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = prevline[x] ^ mix; else line[x] = prevline[x]; ) } break; case 3: /* Colour */ REPEAT(line[x] = colour2) break; case 4: /* Copy */ REPEAT(line[x] = CVAL(input)) break; case 8: /* Bicolour */ REPEAT ( if (bicolour) { line[x] = colour2; bicolour = False; } else { line[x] = colour1; bicolour = True; count++; } ) break; case 0xd: /* White */ REPEAT(line[x] = 0xff) break; case 0xe: /* Black */ REPEAT(line[x] = 0) break; default: logger(Core, Warning, "bitmap_decompress(), unhandled bitmap opcode 0x%x", opcode); return False; } } } return True; } /* 2 byte bitmap decompress */ static RD_BOOL bitmap_decompress2(uint8 * output, int width, int height, uint8 * input, int size) { uint8 *end = input + size; uint16 *prevline = NULL, *line = NULL; int opcode, count, offset, isfillormix, x = width; int lastopcode = -1, insertmix = False, bicolour = False; uint8 code; uint16 colour1 = 0, colour2 = 0; uint8 mixmask, mask = 0; uint16 mix = 0xffff; int fom_mask = 0; while (input < end) { fom_mask = 0; code = CVAL(input); opcode = code >> 4; /* Handle different opcode forms */ switch (opcode) { case 0xc: case 0xd: case 0xe: opcode -= 6; count = code & 0xf; offset = 16; break; case 0xf: opcode = code & 0xf; if (opcode < 9) { count = CVAL(input); count |= CVAL(input) << 8; } else { count = (opcode < 0xb) ? 8 : 1; } offset = 0; break; default: opcode >>= 1; count = code & 0x1f; offset = 32; break; } /* Handle strange cases for counts */ if (offset != 0) { isfillormix = ((opcode == 2) || (opcode == 7)); if (count == 0) { if (isfillormix) count = CVAL(input) + 1; else count = CVAL(input) + offset; } else if (isfillormix) { count <<= 3; } } /* Read preliminary data */ switch (opcode) { case 0: /* Fill */ if ((lastopcode == opcode) && !((x == width) && (prevline == NULL))) insertmix = True; break; case 8: /* Bicolour */ CVAL2(input, colour1); CVAL2(input, colour2); break; case 3: /* Colour */ CVAL2(input, colour2); break; case 6: /* SetMix/Mix */ case 7: /* SetMix/FillOrMix */ CVAL2(input, mix); opcode -= 5; break; case 9: /* FillOrMix_1 */ mask = 0x03; opcode = 0x02; fom_mask = 3; break; case 0x0a: /* FillOrMix_2 */ mask = 0x05; opcode = 0x02; fom_mask = 5; break; } lastopcode = opcode; mixmask = 0; /* Output body */ while (count > 0) { if (x >= width) { if (height <= 0) return False; x = 0; height--; prevline = line; line = ((uint16 *) output) + height * width; } switch (opcode) { case 0: /* Fill */ if (insertmix) { if (prevline == NULL) line[x] = mix; else line[x] = prevline[x] ^ mix; insertmix = False; count--; x++; } if (prevline == NULL) { REPEAT(line[x] = 0) } else { REPEAT(line[x] = prevline[x]) } break; case 1: /* Mix */ if (prevline == NULL) { REPEAT(line[x] = mix) } else { REPEAT(line[x] = prevline[x] ^ mix) } break; case 2: /* Fill or Mix */ if (prevline == NULL) { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = mix; else line[x] = 0; ) } else { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = prevline[x] ^ mix; else line[x] = prevline[x]; ) } break; case 3: /* Colour */ REPEAT(line[x] = colour2) break; case 4: /* Copy */ REPEAT(CVAL2(input, line[x])) break; case 8: /* Bicolour */ REPEAT ( if (bicolour) { line[x] = colour2; bicolour = False; } else { line[x] = colour1; bicolour = True; count++; } ) break; case 0xd: /* White */ REPEAT(line[x] = 0xffff) break; case 0xe: /* Black */ REPEAT(line[x] = 0) break; default: logger(Core, Warning, "bitmap_decompress2(), unhandled bitmap opcode 0x%x", opcode); return False; } } } return True; } /* 3 byte bitmap decompress */ static RD_BOOL bitmap_decompress3(uint8 * output, int width, int height, uint8 * input, int size) { uint8 *end = input + size; uint8 *prevline = NULL, *line = NULL; int opcode, count, offset, isfillormix, x = width; int lastopcode = -1, insertmix = False, bicolour = False; uint8 code; uint8 colour1[3] = {0, 0, 0}, colour2[3] = {0, 0, 0}; uint8 mixmask, mask = 0; uint8 mix[3] = {0xff, 0xff, 0xff}; int fom_mask = 0; while (input < end) { fom_mask = 0; code = CVAL(input); opcode = code >> 4; /* Handle different opcode forms */ switch (opcode) { case 0xc: case 0xd: case 0xe: opcode -= 6; count = code & 0xf; offset = 16; break; case 0xf: opcode = code & 0xf; if (opcode < 9) { count = CVAL(input); count |= CVAL(input) << 8; } else { count = (opcode < 0xb) ? 8 : 1; } offset = 0; break; default: opcode >>= 1; count = code & 0x1f; offset = 32; break; } /* Handle strange cases for counts */ if (offset != 0) { isfillormix = ((opcode == 2) || (opcode == 7)); if (count == 0) { if (isfillormix) count = CVAL(input) + 1; else count = CVAL(input) + offset; } else if (isfillormix) { count <<= 3; } } /* Read preliminary data */ switch (opcode) { case 0: /* Fill */ if ((lastopcode == opcode) && !((x == width) && (prevline == NULL))) insertmix = True; break; case 8: /* Bicolour */ colour1[0] = CVAL(input); colour1[1] = CVAL(input); colour1[2] = CVAL(input); colour2[0] = CVAL(input); colour2[1] = CVAL(input); colour2[2] = CVAL(input); break; case 3: /* Colour */ colour2[0] = CVAL(input); colour2[1] = CVAL(input); colour2[2] = CVAL(input); break; case 6: /* SetMix/Mix */ case 7: /* SetMix/FillOrMix */ mix[0] = CVAL(input); mix[1] = CVAL(input); mix[2] = CVAL(input); opcode -= 5; break; case 9: /* FillOrMix_1 */ mask = 0x03; opcode = 0x02; fom_mask = 3; break; case 0x0a: /* FillOrMix_2 */ mask = 0x05; opcode = 0x02; fom_mask = 5; break; } lastopcode = opcode; mixmask = 0; /* Output body */ while (count > 0) { if (x >= width) { if (height <= 0) return False; x = 0; height--; prevline = line; line = output + height * (width * 3); } switch (opcode) { case 0: /* Fill */ if (insertmix) { if (prevline == NULL) { line[x * 3] = mix[0]; line[x * 3 + 1] = mix[1]; line[x * 3 + 2] = mix[2]; } else { line[x * 3] = prevline[x * 3] ^ mix[0]; line[x * 3 + 1] = prevline[x * 3 + 1] ^ mix[1]; line[x * 3 + 2] = prevline[x * 3 + 2] ^ mix[2]; } insertmix = False; count--; x++; } if (prevline == NULL) { REPEAT ( line[x * 3] = 0; line[x * 3 + 1] = 0; line[x * 3 + 2] = 0; ) } else { REPEAT ( line[x * 3] = prevline[x * 3]; line[x * 3 + 1] = prevline[x * 3 + 1]; line[x * 3 + 2] = prevline[x * 3 + 2]; ) } break; case 1: /* Mix */ if (prevline == NULL) { REPEAT ( line[x * 3] = mix[0]; line[x * 3 + 1] = mix[1]; line[x * 3 + 2] = mix[2]; ) } else { REPEAT ( line[x * 3] = prevline[x * 3] ^ mix[0]; line[x * 3 + 1] = prevline[x * 3 + 1] ^ mix[1]; line[x * 3 + 2] = prevline[x * 3 + 2] ^ mix[2]; ) } break; case 2: /* Fill or Mix */ if (prevline == NULL) { REPEAT ( MASK_UPDATE(); if (mask & mixmask) { line[x * 3] = mix[0]; line[x * 3 + 1] = mix[1]; line[x * 3 + 2] = mix[2]; } else { line[x * 3] = 0; line[x * 3 + 1] = 0; line[x * 3 + 2] = 0; } ) } else { REPEAT ( MASK_UPDATE(); if (mask & mixmask) { line[x * 3] = prevline[x * 3] ^ mix [0]; line[x * 3 + 1] = prevline[x * 3 + 1] ^ mix [1]; line[x * 3 + 2] = prevline[x * 3 + 2] ^ mix [2]; } else { line[x * 3] = prevline[x * 3]; line[x * 3 + 1] = prevline[x * 3 + 1]; line[x * 3 + 2] = prevline[x * 3 + 2]; } ) } break; case 3: /* Colour */ REPEAT ( line[x * 3] = colour2 [0]; line[x * 3 + 1] = colour2 [1]; line[x * 3 + 2] = colour2 [2]; ) break; case 4: /* Copy */ REPEAT ( line[x * 3] = CVAL(input); line[x * 3 + 1] = CVAL(input); line[x * 3 + 2] = CVAL(input); ) break; case 8: /* Bicolour */ REPEAT ( if (bicolour) { line[x * 3] = colour2[0]; line[x * 3 + 1] = colour2[1]; line[x * 3 + 2] = colour2[2]; bicolour = False; } else { line[x * 3] = colour1[0]; line[x * 3 + 1] = colour1[1]; line[x * 3 + 2] = colour1[2]; bicolour = True; count++; } ) break; case 0xd: /* White */ REPEAT ( line[x * 3] = 0xff; line[x * 3 + 1] = 0xff; line[x * 3 + 2] = 0xff; ) break; case 0xe: /* Black */ REPEAT ( line[x * 3] = 0; line[x * 3 + 1] = 0; line[x * 3 + 2] = 0; ) break; default: logger(Core, Warning, "bitmap_decompress3(), unhandled bitmap opcode 0x%x", opcode); return False; } } } return True; } /* decompress a colour plane */ static int process_plane(uint8 * in, int width, int height, uint8 * out, int size) { UNUSED(size); int indexw; int indexh; int code; int collen; int replen; int color; int x; int revcode; uint8 * last_line; uint8 * this_line; uint8 * org_in; uint8 * org_out; org_in = in; org_out = out; last_line = 0; indexh = 0; while (indexh < height) { out = (org_out + width * height * 4) - ((indexh + 1) * width * 4); color = 0; this_line = out; indexw = 0; if (last_line == 0) { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (indexw < width && collen > 0) { color = CVAL(in); *out = color; out += 4; indexw++; collen--; } while (indexw < width && replen > 0) { *out = color; out += 4; indexw++; replen--; } } } else { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (indexw < width && collen > 0) { x = CVAL(in); if (x & 1) { x = x >> 1; x = x + 1; color = -x; } else { x = x >> 1; color = x; } x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; collen--; } while (indexw < width && replen > 0) { x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; replen--; } } } indexh++; last_line = this_line; } return (int) (in - org_in); } /* 4 byte bitmap decompress */ static RD_BOOL bitmap_decompress4(uint8 * output, int width, int height, uint8 * input, int size) { int code; int bytes_pro; int total_pro; code = CVAL(input); if (code != 0x10) { return False; } total_pro = 1; bytes_pro = process_plane(input, width, height, output + 3, size - total_pro); total_pro += bytes_pro; input += bytes_pro; bytes_pro = process_plane(input, width, height, output + 2, size - total_pro); total_pro += bytes_pro; input += bytes_pro; bytes_pro = process_plane(input, width, height, output + 1, size - total_pro); total_pro += bytes_pro; input += bytes_pro; bytes_pro = process_plane(input, width, height, output + 0, size - total_pro); total_pro += bytes_pro; return size == total_pro; } /* main decompress function */ RD_BOOL bitmap_decompress(uint8 * output, int width, int height, uint8 * input, int size, int Bpp) { RD_BOOL rv = False; switch (Bpp) { case 1: rv = bitmap_decompress1(output, width, height, input, size); break; case 2: rv = bitmap_decompress2(output, width, height, input, size); break; case 3: rv = bitmap_decompress3(output, width, height, input, size); break; case 4: rv = bitmap_decompress4(output, width, height, input, size); break; default: logger(Core, Debug, "bitmap_decompress(), unhandled BPP %d", Bpp); break; } return rv; } /* *INDENT-ON* */
./CrossVul/dataset_final_sorted/CWE-125/c/good_486_1
crossvul-cpp_data_good_1357_0
/* * Copyright (c) 2018, SUSE LLC. * * This program is licensed under the BSD license, read LICENSE.BSD * for further information */ /* * repodata.c * * Manage data coming from one repository * * a repository can contain multiple repodata entries, consisting of * different sets of keys and different sets of solvables */ #define _GNU_SOURCE #include <string.h> #include <fnmatch.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <regex.h> #include "repo.h" #include "pool.h" #include "poolid_private.h" #include "util.h" #include "hash.h" #include "chksum.h" #include "repopack.h" #include "repopage.h" #ifdef _WIN32 #include "strfncs.h" #endif #define REPODATA_BLOCK 255 static unsigned char *data_skip_key(Repodata *data, unsigned char *dp, Repokey *key); void repodata_initdata(Repodata *data, Repo *repo, int localpool) { memset(data, 0, sizeof (*data)); data->repodataid = data - repo->repodata; data->repo = repo; data->localpool = localpool; if (localpool) stringpool_init_empty(&data->spool); /* dirpool_init(&data->dirpool); just zeros out again */ data->keys = solv_calloc(1, sizeof(Repokey)); data->nkeys = 1; data->schemata = solv_calloc(1, sizeof(Id)); data->schemadata = solv_calloc(1, sizeof(Id)); data->nschemata = 1; data->schemadatalen = 1; repopagestore_init(&data->store); } void repodata_freedata(Repodata *data) { int i; solv_free(data->keys); solv_free(data->schemata); solv_free(data->schemadata); solv_free(data->schematahash); stringpool_free(&data->spool); dirpool_free(&data->dirpool); solv_free(data->mainschemaoffsets); solv_free(data->incoredata); solv_free(data->incoreoffset); solv_free(data->verticaloffset); repopagestore_free(&data->store); solv_free(data->vincore); if (data->attrs) for (i = 0; i < data->end - data->start; i++) solv_free(data->attrs[i]); solv_free(data->attrs); if (data->xattrs) for (i = 0; i < data->nxattrs; i++) solv_free(data->xattrs[i]); solv_free(data->xattrs); solv_free(data->attrdata); solv_free(data->attriddata); solv_free(data->attrnum64data); solv_free(data->dircache); repodata_free_filelistfilter(data); } void repodata_free(Repodata *data) { Repo *repo = data->repo; int i = data - repo->repodata; if (i == 0) return; repodata_freedata(data); if (i < repo->nrepodata - 1) { /* whoa! this changes the repodataids! */ memmove(repo->repodata + i, repo->repodata + i + 1, (repo->nrepodata - 1 - i) * sizeof(Repodata)); for (; i < repo->nrepodata - 1; i++) repo->repodata[i].repodataid = i; } repo->nrepodata--; if (repo->nrepodata == 1) { repo->repodata = solv_free(repo->repodata); repo->nrepodata = 0; } } void repodata_empty(Repodata *data, int localpool) { void (*loadcallback)(Repodata *) = data->loadcallback; int state = data->state; repodata_freedata(data); repodata_initdata(data, data->repo, localpool); data->state = state; data->loadcallback = loadcallback; } /*************************************************************** * key pool management */ /* this is not so time critical that we need a hash, so we do a simple * linear search */ Id repodata_key2id(Repodata *data, Repokey *key, int create) { Id keyid; for (keyid = 1; keyid < data->nkeys; keyid++) if (data->keys[keyid].name == key->name && data->keys[keyid].type == key->type) { if ((key->type == REPOKEY_TYPE_CONSTANT || key->type == REPOKEY_TYPE_CONSTANTID) && key->size != data->keys[keyid].size) continue; break; } if (keyid == data->nkeys) { if (!create) return 0; /* allocate new key */ data->keys = solv_realloc2(data->keys, data->nkeys + 1, sizeof(Repokey)); data->keys[data->nkeys++] = *key; if (data->verticaloffset) { data->verticaloffset = solv_realloc2(data->verticaloffset, data->nkeys, sizeof(Id)); data->verticaloffset[data->nkeys - 1] = 0; } data->keybits[(key->name >> 3) & (sizeof(data->keybits) - 1)] |= 1 << (key->name & 7); } return keyid; } /*************************************************************** * schema pool management */ #define SCHEMATA_BLOCK 31 #define SCHEMATADATA_BLOCK 255 Id repodata_schema2id(Repodata *data, Id *schema, int create) { int h, len, i; Id *sp, cid; Id *schematahash; if (!*schema) return 0; /* XXX: allow empty schema? */ if ((schematahash = data->schematahash) == 0) { data->schematahash = schematahash = solv_calloc(256, sizeof(Id)); for (i = 1; i < data->nschemata; i++) { for (sp = data->schemadata + data->schemata[i], h = 0; *sp;) h = h * 7 + *sp++; h &= 255; schematahash[h] = i; } data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK); } for (sp = schema, len = 0, h = 0; *sp; len++) h = h * 7 + *sp++; h &= 255; len++; cid = schematahash[h]; if (cid) { if ((data->schemata[cid] + len <= data->schemadatalen) && !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; /* cache conflict, do a slow search */ for (cid = 1; cid < data->nschemata; cid++) if ((data->schemata[cid] + len <= data->schemadatalen) && !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; } /* a new one */ if (!create) return 0; data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK); /* add schema */ memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id)); data->schemata[data->nschemata] = data->schemadatalen; data->schemadatalen += len; schematahash[h] = data->nschemata; #if 0 fprintf(stderr, "schema2id: new schema\n"); #endif return data->nschemata++; } void repodata_free_schemahash(Repodata *data) { data->schematahash = solv_free(data->schematahash); /* shrink arrays */ data->schemata = solv_realloc2(data->schemata, data->nschemata, sizeof(Id)); data->schemadata = solv_realloc2(data->schemadata, data->schemadatalen, sizeof(Id)); } /*************************************************************** * dir pool management */ #ifndef HAVE_STRCHRNUL static inline const char *strchrnul(const char *str, char x) { const char *p = strchr(str, x); return p ? p : str + strlen(str); } #endif #define DIRCACHE_SIZE 41 /* < 1k */ #ifdef DIRCACHE_SIZE struct dircache { Id ids[DIRCACHE_SIZE]; char str[(DIRCACHE_SIZE * (DIRCACHE_SIZE - 1)) / 2]; }; #endif Id repodata_str2dir(Repodata *data, const char *dir, int create) { Id id, parent; #ifdef DIRCACHE_SIZE const char *dirs; #endif const char *dire; if (!*dir) return data->dirpool.ndirs ? 0 : dirpool_add_dir(&data->dirpool, 0, 0, create); while (*dir == '/' && dir[1] == '/') dir++; if (*dir == '/' && !dir[1]) return data->dirpool.ndirs ? 1 : dirpool_add_dir(&data->dirpool, 0, 1, create); parent = 0; #ifdef DIRCACHE_SIZE dirs = dir; if (data->dircache) { int l; struct dircache *dircache = data->dircache; l = strlen(dir); while (l > 0) { if (l < DIRCACHE_SIZE && dircache->ids[l] && !memcmp(dircache->str + l * (l - 1) / 2, dir, l)) { parent = dircache->ids[l]; dir += l; if (!*dir) return parent; while (*dir == '/') dir++; break; } while (--l) if (dir[l] == '/') break; } } #endif while (*dir) { dire = strchrnul(dir, '/'); if (data->localpool) id = stringpool_strn2id(&data->spool, dir, dire - dir, create); else id = pool_strn2id(data->repo->pool, dir, dire - dir, create); if (!id) return 0; parent = dirpool_add_dir(&data->dirpool, parent, id, create); if (!parent) return 0; #ifdef DIRCACHE_SIZE if (!data->dircache) data->dircache = solv_calloc(1, sizeof(struct dircache)); if (data->dircache) { int l = dire - dirs; if (l < DIRCACHE_SIZE) { data->dircache->ids[l] = parent; memcpy(data->dircache->str + l * (l - 1) / 2, dirs, l); } } #endif if (!*dire) break; dir = dire + 1; while (*dir == '/') dir++; } return parent; } void repodata_free_dircache(Repodata *data) { data->dircache = solv_free(data->dircache); } const char * repodata_dir2str(Repodata *data, Id did, const char *suf) { Pool *pool = data->repo->pool; int l = 0; Id parent, comp; const char *comps; char *p; if (!did) return suf ? suf : ""; if (did == 1 && !suf) return "/"; parent = did; while (parent) { comp = dirpool_compid(&data->dirpool, parent); comps = stringpool_id2str(data->localpool ? &data->spool : &pool->ss, comp); l += strlen(comps); parent = dirpool_parent(&data->dirpool, parent); if (parent) l++; } if (suf) l += strlen(suf) + 1; p = pool_alloctmpspace(pool, l + 1) + l; *p = 0; if (suf) { p -= strlen(suf); strcpy(p, suf); *--p = '/'; } parent = did; while (parent) { comp = dirpool_compid(&data->dirpool, parent); comps = stringpool_id2str(data->localpool ? &data->spool : &pool->ss, comp); l = strlen(comps); p -= l; strncpy(p, comps, l); parent = dirpool_parent(&data->dirpool, parent); if (parent) *--p = '/'; } return p; } /*************************************************************** * data management */ static inline unsigned char * data_skip_schema(Repodata *data, unsigned char *dp, Id schema) { Id *keyp = data->schemadata + data->schemata[schema]; for (; *keyp; keyp++) dp = data_skip_key(data, dp, data->keys + *keyp); return dp; } static unsigned char * data_skip_key(Repodata *data, unsigned char *dp, Repokey *key) { int nentries, schema; switch(key->type) { case REPOKEY_TYPE_FIXARRAY: dp = data_read_id(dp, &nentries); if (!nentries) return dp; dp = data_read_id(dp, &schema); while (nentries--) dp = data_skip_schema(data, dp, schema); return dp; case REPOKEY_TYPE_FLEXARRAY: dp = data_read_id(dp, &nentries); while (nentries--) { dp = data_read_id(dp, &schema); dp = data_skip_schema(data, dp, schema); } return dp; default: if (key->storage == KEY_STORAGE_INCORE) dp = data_skip(dp, key->type); else if (key->storage == KEY_STORAGE_VERTICAL_OFFSET) { dp = data_skip(dp, REPOKEY_TYPE_ID); dp = data_skip(dp, REPOKEY_TYPE_ID); } return dp; } } static unsigned char * forward_to_key(Repodata *data, Id keyid, Id *keyp, unsigned char *dp) { Id k; if (!keyid) return 0; if (data->mainschemaoffsets && dp == data->incoredata + data->mainschemaoffsets[0] && keyp == data->schemadata + data->schemata[data->mainschema]) { int i; for (i = 0; (k = *keyp++) != 0; i++) if (k == keyid) return data->incoredata + data->mainschemaoffsets[i]; return 0; } while ((k = *keyp++) != 0) { if (k == keyid) return dp; if (data->keys[k].storage == KEY_STORAGE_VERTICAL_OFFSET) { dp = data_skip(dp, REPOKEY_TYPE_ID); /* skip offset */ dp = data_skip(dp, REPOKEY_TYPE_ID); /* skip length */ continue; } if (data->keys[k].storage != KEY_STORAGE_INCORE) continue; dp = data_skip_key(data, dp, data->keys + k); } return 0; } static unsigned char * get_vertical_data(Repodata *data, Repokey *key, Id off, Id len) { unsigned char *dp; if (len <= 0) return 0; if (off >= data->lastverticaloffset) { off -= data->lastverticaloffset; if ((unsigned int)off + len > data->vincorelen) return 0; return data->vincore + off; } if ((unsigned int)off + len > key->size) return 0; /* we now have the offset, go into vertical */ off += data->verticaloffset[key - data->keys]; /* fprintf(stderr, "key %d page %d\n", key->name, off / REPOPAGE_BLOBSIZE); */ dp = repopagestore_load_page_range(&data->store, off / REPOPAGE_BLOBSIZE, (off + len - 1) / REPOPAGE_BLOBSIZE); data->storestate++; if (dp) dp += off % REPOPAGE_BLOBSIZE; return dp; } static inline unsigned char * get_data(Repodata *data, Repokey *key, unsigned char **dpp, int advance) { unsigned char *dp = *dpp; if (!dp) return 0; if (key->storage == KEY_STORAGE_INCORE) { if (advance) *dpp = data_skip_key(data, dp, key); return dp; } else if (key->storage == KEY_STORAGE_VERTICAL_OFFSET) { Id off, len; dp = data_read_id(dp, &off); dp = data_read_id(dp, &len); if (advance) *dpp = dp; return get_vertical_data(data, key, off, len); } return 0; } void repodata_load(Repodata *data) { if (data->state != REPODATA_STUB) return; if (data->loadcallback) data->loadcallback(data); else data->state = REPODATA_ERROR; } static int maybe_load_repodata_stub(Repodata *data, Id keyname) { if (data->state != REPODATA_STUB) { data->state = REPODATA_ERROR; return 0; } if (keyname) { int i; for (i = 1; i < data->nkeys; i++) if (keyname == data->keys[i].name) break; if (i == data->nkeys) return 0; } repodata_load(data); return data->state == REPODATA_AVAILABLE ? 1 : 0; } static inline int maybe_load_repodata(Repodata *data, Id keyname) { if (keyname && !repodata_precheck_keyname(data, keyname)) return 0; /* do not bother... */ if (data->state == REPODATA_AVAILABLE || data->state == REPODATA_LOADING) return 1; if (data->state == REPODATA_ERROR) return 0; return maybe_load_repodata_stub(data, keyname); } static inline unsigned char * solvid2data(Repodata *data, Id solvid, Id *schemap) { unsigned char *dp = data->incoredata; if (!dp) return 0; if (solvid == SOLVID_META) dp += 1; /* offset of "meta" solvable */ else if (solvid == SOLVID_POS) { Pool *pool = data->repo->pool; if (data->repo != pool->pos.repo) return 0; if (data != data->repo->repodata + pool->pos.repodataid) return 0; dp += pool->pos.dp; if (pool->pos.dp != 1) { *schemap = pool->pos.schema; return dp; } } else { if (solvid < data->start || solvid >= data->end) return 0; dp += data->incoreoffset[solvid - data->start]; } return data_read_id(dp, schemap); } /************************************************************************ * data lookup */ static unsigned char * find_key_data(Repodata *data, Id solvid, Id keyname, Repokey **keypp) { unsigned char *dp; Id schema, *keyp, *kp; Repokey *key; if (!maybe_load_repodata(data, keyname)) return 0; dp = solvid2data(data, solvid, &schema); if (!dp) return 0; keyp = data->schemadata + data->schemata[schema]; for (kp = keyp; *kp; kp++) if (data->keys[*kp].name == keyname) break; if (!*kp) return 0; *keypp = key = data->keys + *kp; if (key->type == REPOKEY_TYPE_DELETED) return 0; if (key->type == REPOKEY_TYPE_VOID || key->type == REPOKEY_TYPE_CONSTANT || key->type == REPOKEY_TYPE_CONSTANTID) return dp; /* no need to forward... */ if (key->storage != KEY_STORAGE_INCORE && key->storage != KEY_STORAGE_VERTICAL_OFFSET) return 0; /* get_data will not work, no need to forward */ dp = forward_to_key(data, *kp, keyp, dp); if (!dp) return 0; return get_data(data, key, &dp, 0); } static const Id * repodata_lookup_schemakeys(Repodata *data, Id solvid) { Id schema; if (!maybe_load_repodata(data, 0)) return 0; if (!solvid2data(data, solvid, &schema)) return 0; return data->schemadata + data->schemata[schema]; } static Id * alloc_keyskip() { Id *keyskip = solv_calloc(3 + 256, sizeof(Id)); keyskip[0] = 256; keyskip[1] = keyskip[2] = 1; return keyskip; } Id * repodata_fill_keyskip(Repodata *data, Id solvid, Id *keyskip) { const Id *keyp; Id maxkeyname, value; keyp = repodata_lookup_schemakeys(data, solvid); if (!keyp) return keyskip; /* no keys for this solvid */ if (!keyskip) keyskip = alloc_keyskip(); maxkeyname = keyskip[0]; value = keyskip[1] + data->repodataid; for (; *keyp; keyp++) { Id keyname = data->keys[*keyp].name; if (keyname >= maxkeyname) { int newmax = (keyname | 255) + 1; keyskip = solv_realloc2(keyskip, 3 + newmax, sizeof(Id)); memset(keyskip + (3 + maxkeyname), 0, (newmax - maxkeyname) * sizeof(Id)); keyskip[0] = maxkeyname = newmax; } keyskip[3 + keyname] = value; } return keyskip; } Id repodata_lookup_type(Repodata *data, Id solvid, Id keyname) { Id schema, *keyp, *kp; if (!maybe_load_repodata(data, keyname)) return 0; if (!solvid2data(data, solvid, &schema)) return 0; keyp = data->schemadata + data->schemata[schema]; for (kp = keyp; *kp; kp++) if (data->keys[*kp].name == keyname) return data->keys[*kp].type; return 0; } Id repodata_lookup_id(Repodata *data, Id solvid, Id keyname) { unsigned char *dp; Repokey *key; Id id; dp = find_key_data(data, solvid, keyname, &key); if (!dp) return 0; if (key->type == REPOKEY_TYPE_CONSTANTID) return key->size; if (key->type != REPOKEY_TYPE_ID) return 0; dp = data_read_id(dp, &id); return id; } const char * repodata_lookup_str(Repodata *data, Id solvid, Id keyname) { unsigned char *dp; Repokey *key; Id id; dp = find_key_data(data, solvid, keyname, &key); if (!dp) return 0; if (key->type == REPOKEY_TYPE_STR) return (const char *)dp; if (key->type == REPOKEY_TYPE_CONSTANTID) id = key->size; else if (key->type == REPOKEY_TYPE_ID) dp = data_read_id(dp, &id); else return 0; if (data->localpool) return stringpool_id2str(&data->spool, id); return pool_id2str(data->repo->pool, id); } unsigned long long repodata_lookup_num(Repodata *data, Id solvid, Id keyname, unsigned long long notfound) { unsigned char *dp; Repokey *key; unsigned int high, low; dp = find_key_data(data, solvid, keyname, &key); if (!dp) return notfound; switch (key->type) { case REPOKEY_TYPE_NUM: data_read_num64(dp, &low, &high); return (unsigned long long)high << 32 | low; case REPOKEY_TYPE_CONSTANT: return key->size; default: return notfound; } } int repodata_lookup_void(Repodata *data, Id solvid, Id keyname) { return repodata_lookup_type(data, solvid, keyname) == REPOKEY_TYPE_VOID ? 1 : 0; } const unsigned char * repodata_lookup_bin_checksum(Repodata *data, Id solvid, Id keyname, Id *typep) { unsigned char *dp; Repokey *key; dp = find_key_data(data, solvid, keyname, &key); if (!dp) return 0; switch (key->type) { case_CHKSUM_TYPES: break; default: return 0; } *typep = key->type; return dp; } int repodata_lookup_idarray(Repodata *data, Id solvid, Id keyname, Queue *q) { unsigned char *dp; Repokey *key; Id id; int eof = 0; queue_empty(q); dp = find_key_data(data, solvid, keyname, &key); if (!dp) return 0; switch (key->type) { case REPOKEY_TYPE_CONSTANTID: queue_push(q, key->size); break; case REPOKEY_TYPE_ID: dp = data_read_id(dp, &id); queue_push(q, id); break; case REPOKEY_TYPE_IDARRAY: for (;;) { dp = data_read_ideof(dp, &id, &eof); queue_push(q, id); if (eof) break; } break; default: return 0; } return 1; } const void * repodata_lookup_binary(Repodata *data, Id solvid, Id keyname, int *lenp) { unsigned char *dp; Repokey *key; Id len; dp = find_key_data(data, solvid, keyname, &key); if (!dp || key->type != REPOKEY_TYPE_BINARY) { *lenp = 0; return 0; } dp = data_read_id(dp, &len); *lenp = len; return dp; } /* highly specialized function to speed up fileprovides adding. * - repodata must be available * - solvid must be >= data->start and < data->end * - returns NULL is not found, a "" entry if wrong type * - also returns wrong type for REPOKEY_TYPE_DELETED */ const unsigned char * repodata_lookup_packed_dirstrarray(Repodata *data, Id solvid, Id keyname) { static unsigned char wrongtype[2] = { 0x00 /* dir id 0 */, 0 /* "" */ }; unsigned char *dp; Id schema, *keyp, *kp; Repokey *key; if (!data->incoredata || !data->incoreoffset[solvid - data->start]) return 0; dp = data->incoredata + data->incoreoffset[solvid - data->start]; dp = data_read_id(dp, &schema); keyp = data->schemadata + data->schemata[schema]; for (kp = keyp; *kp; kp++) if (data->keys[*kp].name == keyname) break; if (!*kp) return 0; key = data->keys + *kp; if (key->type != REPOKEY_TYPE_DIRSTRARRAY) return wrongtype; dp = forward_to_key(data, *kp, keyp, dp); if (key->storage == KEY_STORAGE_INCORE) return dp; if (key->storage == KEY_STORAGE_VERTICAL_OFFSET && dp) { Id off, len; dp = data_read_id(dp, &off); data_read_id(dp, &len); return get_vertical_data(data, key, off, len); } return 0; } /* id translation functions */ Id repodata_globalize_id(Repodata *data, Id id, int create) { if (!id || !data || !data->localpool) return id; return pool_str2id(data->repo->pool, stringpool_id2str(&data->spool, id), create); } Id repodata_localize_id(Repodata *data, Id id, int create) { if (!id || !data || !data->localpool) return id; return stringpool_str2id(&data->spool, pool_id2str(data->repo->pool, id), create); } Id repodata_translate_id(Repodata *data, Repodata *fromdata, Id id, int create) { const char *s; if (!id || !data || !fromdata) return id; if (data == fromdata || (!data->localpool && !fromdata->localpool)) return id; if (fromdata->localpool) s = stringpool_id2str(&fromdata->spool, id); else s = pool_id2str(data->repo->pool, id); if (data->localpool) return stringpool_str2id(&data->spool, s, create); else return pool_str2id(data->repo->pool, s, create); } Id repodata_translate_dir_slow(Repodata *data, Repodata *fromdata, Id dir, int create, Id *cache) { Id parent, compid; if (!dir) { /* make sure that the dirpool has an entry */ if (create && !data->dirpool.ndirs) dirpool_add_dir(&data->dirpool, 0, 0, create); return 0; } parent = dirpool_parent(&fromdata->dirpool, dir); if (parent) { if (!(parent = repodata_translate_dir(data, fromdata, parent, create, cache))) return 0; } compid = dirpool_compid(&fromdata->dirpool, dir); if (compid > 1 && (data->localpool || fromdata->localpool)) { if (!(compid = repodata_translate_id(data, fromdata, compid, create))) return 0; } if (!(compid = dirpool_add_dir(&data->dirpool, parent, compid, create))) return 0; if (cache) { cache[(dir & 255) * 2] = dir; cache[(dir & 255) * 2 + 1] = compid; } return compid; } /************************************************************************ * uninternalized lookup / search */ static void data_fetch_uninternalized(Repodata *data, Repokey *key, Id value, KeyValue *kv) { Id *array; kv->eof = 1; switch (key->type) { case REPOKEY_TYPE_STR: kv->str = (const char *)data->attrdata + value; return; case REPOKEY_TYPE_CONSTANT: kv->num2 = 0; kv->num = key->size; return; case REPOKEY_TYPE_CONSTANTID: kv->id = key->size; return; case REPOKEY_TYPE_NUM: kv->num2 = 0; kv->num = value; if (value & 0x80000000) { kv->num = (unsigned int)data->attrnum64data[value ^ 0x80000000]; kv->num2 = (unsigned int)(data->attrnum64data[value ^ 0x80000000] >> 32); } return; case_CHKSUM_TYPES: kv->num = 0; /* not stringified */ kv->str = (const char *)data->attrdata + value; return; case REPOKEY_TYPE_BINARY: kv->str = (const char *)data_read_id(data->attrdata + value, (Id *)&kv->num); return; case REPOKEY_TYPE_IDARRAY: array = data->attriddata + (value + kv->entry); kv->id = array[0]; kv->eof = array[1] ? 0 : 1; return; case REPOKEY_TYPE_DIRSTRARRAY: kv->num = 0; /* not stringified */ array = data->attriddata + (value + kv->entry * 2); kv->id = array[0]; kv->str = (const char *)data->attrdata + array[1]; kv->eof = array[2] ? 0 : 1; return; case REPOKEY_TYPE_DIRNUMNUMARRAY: array = data->attriddata + (value + kv->entry * 3); kv->id = array[0]; kv->num = array[1]; kv->num2 = array[2]; kv->eof = array[3] ? 0 : 1; return; case REPOKEY_TYPE_FIXARRAY: case REPOKEY_TYPE_FLEXARRAY: array = data->attriddata + (value + kv->entry); kv->id = array[0]; /* the handle */ kv->eof = array[1] ? 0 : 1; return; default: kv->id = value; return; } } Repokey * repodata_lookup_kv_uninternalized(Repodata *data, Id solvid, Id keyname, KeyValue *kv) { Id *ap; if (!data->attrs || solvid < data->start || solvid >= data->end) return 0; ap = data->attrs[solvid - data->start]; if (!ap) return 0; for (; *ap; ap += 2) { Repokey *key = data->keys + *ap; if (key->name != keyname) continue; data_fetch_uninternalized(data, key, ap[1], kv); return key; } return 0; } void repodata_search_uninternalized(Repodata *data, Id solvid, Id keyname, int flags, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata) { Id *ap; int stop; Solvable *s; KeyValue kv; if (!data->attrs || solvid < data->start || solvid >= data->end) return; ap = data->attrs[solvid - data->start]; if (!ap) return; for (; *ap; ap += 2) { Repokey *key = data->keys + *ap; if (keyname && key->name != keyname) continue; s = solvid > 0 ? data->repo->pool->solvables + solvid : 0; kv.entry = 0; do { data_fetch_uninternalized(data, key, ap[1], &kv); stop = callback(cbdata, s, data, key, &kv); kv.entry++; } while (!kv.eof && !stop); if (keyname || stop > SEARCH_NEXT_KEY) return; } } /************************************************************************ * data search */ const char * repodata_stringify(Pool *pool, Repodata *data, Repokey *key, KeyValue *kv, int flags) { switch (key->type) { case REPOKEY_TYPE_ID: case REPOKEY_TYPE_CONSTANTID: case REPOKEY_TYPE_IDARRAY: if (data && data->localpool) kv->str = stringpool_id2str(&data->spool, kv->id); else kv->str = pool_id2str(pool, kv->id); if ((flags & SEARCH_SKIP_KIND) != 0 && key->storage == KEY_STORAGE_SOLVABLE && (key->name == SOLVABLE_NAME || key->type == REPOKEY_TYPE_IDARRAY)) { const char *s; for (s = kv->str; *s >= 'a' && *s <= 'z'; s++) ; if (*s == ':' && s > kv->str) kv->str = s + 1; } return kv->str; case REPOKEY_TYPE_STR: return kv->str; case REPOKEY_TYPE_DIRSTRARRAY: if (!(flags & SEARCH_FILES)) return kv->str; /* match just the basename */ if (kv->num) return kv->str; /* already stringified */ /* Put the full filename into kv->str. */ kv->str = repodata_dir2str(data, kv->id, kv->str); kv->num = 1; /* mark stringification */ return kv->str; case_CHKSUM_TYPES: if (!(flags & SEARCH_CHECKSUMS)) return 0; /* skip em */ if (kv->num) return kv->str; /* already stringified */ kv->str = repodata_chk2str(data, key->type, (const unsigned char *)kv->str); kv->num = 1; /* mark stringification */ return kv->str; default: return 0; } } /* this is an internal hack to pass the parent kv to repodata_search_keyskip */ struct subschema_data { void *cbdata; Id solvid; KeyValue *parent; }; void repodata_search_arrayelement(Repodata *data, Id solvid, Id keyname, int flags, KeyValue *kv, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata) { repodata_search_keyskip(data, solvid, keyname, flags | SEARCH_SUBSCHEMA, (Id *)kv, callback, cbdata); } static int repodata_search_array(Repodata *data, Id solvid, Id keyname, int flags, Repokey *key, KeyValue *kv, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata) { Solvable *s = solvid > 0 ? data->repo->pool->solvables + solvid : 0; unsigned char *dp = (unsigned char *)kv->str; int stop; Id schema = 0; if (!dp || kv->entry != -1) return 0; while (++kv->entry < (int)kv->num) { if (kv->entry) dp = data_skip_schema(data, dp, schema); if (kv->entry == 0 || key->type == REPOKEY_TYPE_FLEXARRAY) dp = data_read_id(dp, &schema); kv->id = schema; kv->str = (const char *)dp; kv->eof = kv->entry == kv->num - 1 ? 1 : 0; stop = callback(cbdata, s, data, key, kv); if (stop && stop != SEARCH_ENTERSUB) return stop; if ((flags & SEARCH_SUB) != 0 || stop == SEARCH_ENTERSUB) repodata_search_keyskip(data, solvid, keyname, flags | SEARCH_SUBSCHEMA, (Id *)kv, callback, cbdata); } if ((flags & SEARCH_ARRAYSENTINEL) != 0) { if (kv->entry) dp = data_skip_schema(data, dp, schema); kv->id = 0; kv->str = (const char *)dp; kv->eof = 2; return callback(cbdata, s, data, key, kv); } return 0; } /* search a specific repodata */ void repodata_search_keyskip(Repodata *data, Id solvid, Id keyname, int flags, Id *keyskip, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata) { Id schema; Repokey *key; Id keyid, *kp, *keyp; unsigned char *dp, *ddp; int onekey = 0; int stop; KeyValue kv; Solvable *s; if (!maybe_load_repodata(data, keyname)) return; if ((flags & SEARCH_SUBSCHEMA) != 0) { flags ^= SEARCH_SUBSCHEMA; kv.parent = (KeyValue *)keyskip; keyskip = 0; schema = kv.parent->id; dp = (unsigned char *)kv.parent->str; } else { schema = 0; dp = solvid2data(data, solvid, &schema); if (!dp) return; kv.parent = 0; } s = solvid > 0 ? data->repo->pool->solvables + solvid : 0; keyp = data->schemadata + data->schemata[schema]; if (keyname) { /* search for a specific key */ for (kp = keyp; *kp; kp++) if (data->keys[*kp].name == keyname) break; if (!*kp) return; dp = forward_to_key(data, *kp, keyp, dp); if (!dp) return; keyp = kp; onekey = 1; } while ((keyid = *keyp++) != 0) { stop = 0; key = data->keys + keyid; ddp = get_data(data, key, &dp, *keyp && !onekey ? 1 : 0); if (keyskip && (key->name >= keyskip[0] || keyskip[3 + key->name] != keyskip[1] + data->repodataid)) { if (onekey) return; continue; } if (key->type == REPOKEY_TYPE_DELETED && !(flags & SEARCH_KEEP_TYPE_DELETED)) { if (onekey) return; continue; } if (key->type == REPOKEY_TYPE_FLEXARRAY || key->type == REPOKEY_TYPE_FIXARRAY) { kv.entry = -1; ddp = data_read_id(ddp, (Id *)&kv.num); kv.str = (const char *)ddp; stop = repodata_search_array(data, solvid, 0, flags, key, &kv, callback, cbdata); if (onekey || stop > SEARCH_NEXT_KEY) return; continue; } kv.entry = 0; do { ddp = data_fetch(ddp, &kv, key); if (!ddp) break; stop = callback(cbdata, s, data, key, &kv); kv.entry++; } while (!kv.eof && !stop); if (onekey || stop > SEARCH_NEXT_KEY) return; } } void repodata_search(Repodata *data, Id solvid, Id keyname, int flags, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata) { repodata_search_keyskip(data, solvid, keyname, flags, 0, callback, cbdata); } void repodata_setpos_kv(Repodata *data, KeyValue *kv) { Pool *pool = data->repo->pool; if (!kv) pool_clear_pos(pool); else { pool->pos.repo = data->repo; pool->pos.repodataid = data - data->repo->repodata; pool->pos.dp = (unsigned char *)kv->str - data->incoredata; pool->pos.schema = kv->id; } } /************************************************************************ * data iterator functions */ static inline Id * solvabledata_fetch(Solvable *s, KeyValue *kv, Id keyname) { kv->id = keyname; switch (keyname) { case SOLVABLE_NAME: kv->eof = 1; return &s->name; case SOLVABLE_ARCH: kv->eof = 1; return &s->arch; case SOLVABLE_EVR: kv->eof = 1; return &s->evr; case SOLVABLE_VENDOR: kv->eof = 1; return &s->vendor; case SOLVABLE_PROVIDES: kv->eof = 0; return s->provides ? s->repo->idarraydata + s->provides : 0; case SOLVABLE_OBSOLETES: kv->eof = 0; return s->obsoletes ? s->repo->idarraydata + s->obsoletes : 0; case SOLVABLE_CONFLICTS: kv->eof = 0; return s->conflicts ? s->repo->idarraydata + s->conflicts : 0; case SOLVABLE_REQUIRES: kv->eof = 0; return s->requires ? s->repo->idarraydata + s->requires : 0; case SOLVABLE_RECOMMENDS: kv->eof = 0; return s->recommends ? s->repo->idarraydata + s->recommends : 0; case SOLVABLE_SUPPLEMENTS: kv->eof = 0; return s->supplements ? s->repo->idarraydata + s->supplements : 0; case SOLVABLE_SUGGESTS: kv->eof = 0; return s->suggests ? s->repo->idarraydata + s->suggests : 0; case SOLVABLE_ENHANCES: kv->eof = 0; return s->enhances ? s->repo->idarraydata + s->enhances : 0; case RPM_RPMDBID: kv->eof = 1; return s->repo->rpmdbid ? s->repo->rpmdbid + (s - s->repo->pool->solvables - s->repo->start) : 0; default: return 0; } } int datamatcher_init(Datamatcher *ma, const char *match, int flags) { match = match ? solv_strdup(match) : 0; ma->match = match; ma->flags = flags; ma->error = 0; ma->matchdata = 0; if ((flags & SEARCH_STRINGMASK) == SEARCH_REGEX) { ma->matchdata = solv_calloc(1, sizeof(regex_t)); ma->error = regcomp((regex_t *)ma->matchdata, match, REG_EXTENDED | REG_NOSUB | REG_NEWLINE | ((flags & SEARCH_NOCASE) ? REG_ICASE : 0)); if (ma->error) { solv_free(ma->matchdata); ma->flags = (flags & ~SEARCH_STRINGMASK) | SEARCH_ERROR; } } if ((flags & SEARCH_FILES) != 0 && match) { /* prepare basename check */ if ((flags & SEARCH_STRINGMASK) == SEARCH_STRING || (flags & SEARCH_STRINGMASK) == SEARCH_STRINGEND) { const char *p = strrchr(match, '/'); ma->matchdata = (void *)(p ? p + 1 : match); } else if ((flags & SEARCH_STRINGMASK) == SEARCH_GLOB) { const char *p; for (p = match + strlen(match) - 1; p >= match; p--) if (*p == '[' || *p == ']' || *p == '*' || *p == '?' || *p == '/') break; ma->matchdata = (void *)(p + 1); } } return ma->error; } void datamatcher_free(Datamatcher *ma) { if (ma->match) ma->match = solv_free((char *)ma->match); if ((ma->flags & SEARCH_STRINGMASK) == SEARCH_REGEX && ma->matchdata) { regfree(ma->matchdata); solv_free(ma->matchdata); } ma->matchdata = 0; } int datamatcher_match(Datamatcher *ma, const char *str) { int l; switch ((ma->flags & SEARCH_STRINGMASK)) { case SEARCH_SUBSTRING: if (ma->flags & SEARCH_NOCASE) return strcasestr(str, ma->match) != 0; else return strstr(str, ma->match) != 0; case SEARCH_STRING: if (ma->flags & SEARCH_NOCASE) return !strcasecmp(ma->match, str); else return !strcmp(ma->match, str); case SEARCH_STRINGSTART: if (ma->flags & SEARCH_NOCASE) return !strncasecmp(ma->match, str, strlen(ma->match)); else return !strncmp(ma->match, str, strlen(ma->match)); case SEARCH_STRINGEND: l = strlen(str) - strlen(ma->match); if (l < 0) return 0; if (ma->flags & SEARCH_NOCASE) return !strcasecmp(ma->match, str + l); else return !strcmp(ma->match, str + l); case SEARCH_GLOB: return !fnmatch(ma->match, str, (ma->flags & SEARCH_NOCASE) ? FNM_CASEFOLD : 0); case SEARCH_REGEX: return !regexec((const regex_t *)ma->matchdata, str, 0, NULL, 0); default: return 0; } } /* check if the matcher can match the provides basename */ int datamatcher_checkbasename(Datamatcher *ma, const char *basename) { int l; const char *match = ma->matchdata; if (!match) return 1; switch (ma->flags & SEARCH_STRINGMASK) { case SEARCH_STRING: break; case SEARCH_STRINGEND: if (match != ma->match) break; /* had slash, do exact match on basename */ /* FALLTHROUGH */ case SEARCH_GLOB: /* check if the basename ends with match */ l = strlen(basename) - strlen(match); if (l < 0) return 0; basename += l; break; default: return 1; /* maybe matches */ } if ((ma->flags & SEARCH_NOCASE) != 0) return !strcasecmp(match, basename); else return !strcmp(match, basename); } enum { di_bye, di_enterrepo, di_entersolvable, di_enterrepodata, di_enterschema, di_enterkey, di_nextattr, di_nextkey, di_nextrepodata, di_nextsolvable, di_nextrepo, di_enterarray, di_nextarrayelement, di_entersub, di_leavesub, di_nextsolvablekey, di_entersolvablekey, di_nextsolvableattr }; /* see dataiterator.h for documentation */ int dataiterator_init(Dataiterator *di, Pool *pool, Repo *repo, Id p, Id keyname, const char *match, int flags) { memset(di, 0, sizeof(*di)); di->pool = pool; di->flags = flags & ~SEARCH_THISSOLVID; if (!pool || (repo && repo->pool != pool)) { di->state = di_bye; return -1; } if (match) { int error; if ((error = datamatcher_init(&di->matcher, match, flags)) != 0) { di->state = di_bye; return error; } } di->keyname = keyname; di->keynames[0] = keyname; dataiterator_set_search(di, repo, p); return 0; } void dataiterator_init_clone(Dataiterator *di, Dataiterator *from) { *di = *from; if (di->dupstr) { if (di->dupstr == di->kv.str) di->dupstr = solv_memdup(di->dupstr, di->dupstrn); else { di->dupstr = 0; di->dupstrn = 0; } } memset(&di->matcher, 0, sizeof(di->matcher)); if (from->matcher.match) datamatcher_init(&di->matcher, from->matcher.match, from->matcher.flags); if (di->nparents) { /* fix pointers */ int i; for (i = 1; i < di->nparents; i++) di->parents[i].kv.parent = &di->parents[i - 1].kv; di->kv.parent = &di->parents[di->nparents - 1].kv; } if (di->oldkeyskip) di->oldkeyskip = solv_memdup2(di->oldkeyskip, 3 + di->oldkeyskip[0], sizeof(Id)); if (di->keyskip) di->keyskip = di->oldkeyskip; } int dataiterator_set_match(Dataiterator *di, const char *match, int flags) { di->flags = (flags & ~SEARCH_THISSOLVID) | (di->flags & SEARCH_THISSOLVID); datamatcher_free(&di->matcher); memset(&di->matcher, 0, sizeof(di->matcher)); if (match) { int error; if ((error = datamatcher_init(&di->matcher, match, flags)) != 0) { di->state = di_bye; return error; } } return 0; } void dataiterator_set_search(Dataiterator *di, Repo *repo, Id p) { di->repo = repo; di->repoid = 0; di->flags &= ~SEARCH_THISSOLVID; di->nparents = 0; di->rootlevel = 0; di->repodataid = 1; if (!di->pool->urepos) { di->state = di_bye; return; } if (!repo) { di->repoid = 1; di->repo = di->pool->repos[di->repoid]; } di->state = di_enterrepo; if (p) dataiterator_jump_to_solvid(di, p); } void dataiterator_set_keyname(Dataiterator *di, Id keyname) { di->nkeynames = 0; di->keyname = keyname; di->keynames[0] = keyname; } void dataiterator_prepend_keyname(Dataiterator *di, Id keyname) { int i; if (di->nkeynames >= sizeof(di->keynames)/sizeof(*di->keynames) - 2) { di->state = di_bye; /* sorry */ return; } for (i = di->nkeynames + 1; i > 0; i--) di->keynames[i] = di->keynames[i - 1]; di->keynames[0] = di->keyname = keyname; di->nkeynames++; } void dataiterator_free(Dataiterator *di) { if (di->matcher.match) datamatcher_free(&di->matcher); if (di->dupstr) solv_free(di->dupstr); if (di->oldkeyskip) solv_free(di->oldkeyskip); } static unsigned char * dataiterator_find_keyname(Dataiterator *di, Id keyname) { Id *keyp; Repokey *keys = di->data->keys, *key; unsigned char *dp; for (keyp = di->keyp; *keyp; keyp++) if (keys[*keyp].name == keyname) break; if (!*keyp) return 0; key = keys + *keyp; if (key->type == REPOKEY_TYPE_DELETED) return 0; if (key->storage != KEY_STORAGE_INCORE && key->storage != KEY_STORAGE_VERTICAL_OFFSET) return 0; /* get_data will not work, no need to forward */ dp = forward_to_key(di->data, *keyp, di->keyp, di->dp); if (!dp) return 0; di->keyp = keyp; return dp; } int dataiterator_step(Dataiterator *di) { Id schema; if (di->state == di_nextattr && di->key->storage == KEY_STORAGE_VERTICAL_OFFSET && di->vert_ddp && di->vert_storestate != di->data->storestate) { unsigned int ddpoff = di->ddp - di->vert_ddp; di->vert_off += ddpoff; di->vert_len -= ddpoff; di->ddp = di->vert_ddp = get_vertical_data(di->data, di->key, di->vert_off, di->vert_len); di->vert_storestate = di->data->storestate; if (!di->ddp) di->state = di_nextkey; } for (;;) { switch (di->state) { case di_enterrepo: di_enterrepo: if (!di->repo || (di->repo->disabled && !(di->flags & SEARCH_DISABLED_REPOS))) goto di_nextrepo; if (!(di->flags & SEARCH_THISSOLVID)) { di->solvid = di->repo->start - 1; /* reset solvid iterator */ goto di_nextsolvable; } /* FALLTHROUGH */ case di_entersolvable: di_entersolvable: if (!di->repodataid) goto di_enterrepodata; /* POS case, repodata is set */ if (di->solvid > 0 && !(di->flags & SEARCH_NO_STORAGE_SOLVABLE) && (!di->keyname || (di->keyname >= SOLVABLE_NAME && di->keyname <= RPM_RPMDBID)) && di->nparents - di->rootlevel == di->nkeynames) { extern Repokey repo_solvablekeys[RPM_RPMDBID - SOLVABLE_NAME + 1]; di->key = repo_solvablekeys + (di->keyname ? di->keyname - SOLVABLE_NAME : 0); di->data = 0; goto di_entersolvablekey; } if (di->keyname) { di->data = di->keyname == SOLVABLE_FILELIST ? repo_lookup_filelist_repodata(di->repo, di->solvid, &di->matcher) : repo_lookup_repodata_opt(di->repo, di->solvid, di->keyname); if (!di->data) goto di_nextsolvable; di->repodataid = di->data - di->repo->repodata; di->keyskip = 0; goto di_enterrepodata; } di_leavesolvablekey: di->repodataid = 1; /* reset repodata iterator */ di->keyskip = repo_create_keyskip(di->repo, di->solvid, &di->oldkeyskip); /* FALLTHROUGH */ case di_enterrepodata: di_enterrepodata: if (di->repodataid) { if (di->repodataid >= di->repo->nrepodata) goto di_nextsolvable; di->data = di->repo->repodata + di->repodataid; } if (!maybe_load_repodata(di->data, di->keyname)) goto di_nextrepodata; di->dp = solvid2data(di->data, di->solvid, &schema); if (!di->dp) goto di_nextrepodata; if (di->solvid == SOLVID_POS) di->solvid = di->pool->pos.solvid; /* reset key iterator */ di->keyp = di->data->schemadata + di->data->schemata[schema]; /* FALLTHROUGH */ case di_enterschema: di_enterschema: if (di->keyname) di->dp = dataiterator_find_keyname(di, di->keyname); if (!di->dp || !*di->keyp) { if (di->kv.parent) goto di_leavesub; goto di_nextrepodata; } /* FALLTHROUGH */ case di_enterkey: di_enterkey: di->kv.entry = -1; di->key = di->data->keys + *di->keyp; if (!di->dp) goto di_nextkey; /* this is get_data() modified to store vert_ data */ if (di->key->storage == KEY_STORAGE_VERTICAL_OFFSET) { Id off, len; di->dp = data_read_id(di->dp, &off); di->dp = data_read_id(di->dp, &len); di->vert_ddp = di->ddp = get_vertical_data(di->data, di->key, off, len); di->vert_off = off; di->vert_len = len; di->vert_storestate = di->data->storestate; } else if (di->key->storage == KEY_STORAGE_INCORE) { di->ddp = di->dp; /* start of data */ if (di->keyp[1] && (!di->keyname || (di->flags & SEARCH_SUB) != 0)) di->dp = data_skip_key(di->data, di->dp, di->key); /* advance to next key */ } else di->ddp = 0; if (!di->ddp) goto di_nextkey; if (di->keyskip && (di->key->name >= di->keyskip[0] || di->keyskip[3 + di->key->name] != di->keyskip[1] + di->data->repodataid)) goto di_nextkey; if (di->key->type == REPOKEY_TYPE_DELETED && !(di->flags & SEARCH_KEEP_TYPE_DELETED)) goto di_nextkey; if (di->key->type == REPOKEY_TYPE_FIXARRAY || di->key->type == REPOKEY_TYPE_FLEXARRAY) goto di_enterarray; if (di->nkeynames && di->nparents - di->rootlevel < di->nkeynames) goto di_nextkey; /* FALLTHROUGH */ case di_nextattr: di->kv.entry++; di->ddp = data_fetch(di->ddp, &di->kv, di->key); di->state = di->kv.eof ? di_nextkey : di_nextattr; break; case di_nextkey: di_nextkey: if (!di->keyname && *++di->keyp) goto di_enterkey; if (di->kv.parent) goto di_leavesub; /* FALLTHROUGH */ case di_nextrepodata: di_nextrepodata: if (!di->keyname && di->repodataid && ++di->repodataid < di->repo->nrepodata) goto di_enterrepodata; /* FALLTHROUGH */ case di_nextsolvable: di_nextsolvable: if (!(di->flags & SEARCH_THISSOLVID)) { if (di->solvid < 0) di->solvid = di->repo->start; else di->solvid++; for (; di->solvid < di->repo->end; di->solvid++) { if (di->pool->solvables[di->solvid].repo == di->repo) goto di_entersolvable; } } /* FALLTHROUGH */ case di_nextrepo: di_nextrepo: if (di->repoid > 0) { di->repoid++; di->repodataid = 1; if (di->repoid < di->pool->nrepos) { di->repo = di->pool->repos[di->repoid]; goto di_enterrepo; } } /* FALLTHROUGH */ case di_bye: di_bye: di->state = di_bye; return 0; case di_enterarray: di_enterarray: if (di->key->name == REPOSITORY_SOLVABLES) goto di_nextkey; di->ddp = data_read_id(di->ddp, (Id *)&di->kv.num); di->kv.eof = 0; di->kv.entry = -1; /* FALLTHROUGH */ case di_nextarrayelement: di_nextarrayelement: di->kv.entry++; if (di->kv.entry) di->ddp = data_skip_schema(di->data, di->ddp, di->kv.id); if (di->kv.entry == di->kv.num) { if (di->nkeynames && di->nparents - di->rootlevel < di->nkeynames) goto di_nextkey; if (!(di->flags & SEARCH_ARRAYSENTINEL)) goto di_nextkey; di->kv.str = (char *)di->ddp; di->kv.eof = 2; di->state = di_nextkey; break; } if (di->kv.entry == di->kv.num - 1) di->kv.eof = 1; if (di->key->type == REPOKEY_TYPE_FLEXARRAY || !di->kv.entry) di->ddp = data_read_id(di->ddp, &di->kv.id); di->kv.str = (char *)di->ddp; if (di->nkeynames && di->nparents - di->rootlevel < di->nkeynames) goto di_entersub; if ((di->flags & SEARCH_SUB) != 0) di->state = di_entersub; else di->state = di_nextarrayelement; break; case di_entersub: di_entersub: if (di->nparents == sizeof(di->parents)/sizeof(*di->parents) - 1) goto di_nextarrayelement; /* sorry, full */ di->parents[di->nparents].kv = di->kv; di->parents[di->nparents].dp = di->dp; di->parents[di->nparents].keyp = di->keyp; di->dp = (unsigned char *)di->kv.str; di->keyp = di->data->schemadata + di->data->schemata[di->kv.id]; memset(&di->kv, 0, sizeof(di->kv)); di->kv.parent = &di->parents[di->nparents].kv; di->nparents++; di->keyname = di->keynames[di->nparents - di->rootlevel]; goto di_enterschema; case di_leavesub: di_leavesub: if (di->nparents - 1 < di->rootlevel) goto di_bye; di->nparents--; di->dp = di->parents[di->nparents].dp; di->kv = di->parents[di->nparents].kv; di->keyp = di->parents[di->nparents].keyp; di->key = di->data->keys + *di->keyp; di->ddp = (unsigned char *)di->kv.str; di->keyname = di->keynames[di->nparents - di->rootlevel]; goto di_nextarrayelement; /* special solvable attr handling follows */ case di_nextsolvablekey: di_nextsolvablekey: if (di->keyname) goto di_nextsolvable; if (di->key->name == RPM_RPMDBID) /* reached end of list? */ goto di_leavesolvablekey; di->key++; /* FALLTHROUGH */ case di_entersolvablekey: di_entersolvablekey: di->idp = solvabledata_fetch(di->pool->solvables + di->solvid, &di->kv, di->key->name); if (!di->idp || !*di->idp) goto di_nextsolvablekey; if (di->kv.eof) { /* not an array */ di->kv.id = *di->idp; di->kv.num = *di->idp; /* for rpmdbid */ di->kv.num2 = 0; /* for rpmdbid */ di->kv.entry = 0; di->state = di_nextsolvablekey; break; } di->kv.entry = -1; /* FALLTHROUGH */ case di_nextsolvableattr: di->state = di_nextsolvableattr; di->kv.id = *di->idp++; di->kv.entry++; if (!*di->idp) { di->kv.eof = 1; di->state = di_nextsolvablekey; } break; } /* we have a potential match */ if (di->matcher.match) { const char *str; /* simple pre-check so that we don't need to stringify */ if (di->keyname == SOLVABLE_FILELIST && di->key->type == REPOKEY_TYPE_DIRSTRARRAY && (di->matcher.flags & SEARCH_FILES) != 0) if (!datamatcher_checkbasename(&di->matcher, di->kv.str)) continue; /* now stringify so that we can do the matching */ if (!(str = repodata_stringify(di->pool, di->data, di->key, &di->kv, di->flags))) { if (di->keyname && (di->key->type == REPOKEY_TYPE_FIXARRAY || di->key->type == REPOKEY_TYPE_FLEXARRAY)) return 1; continue; } if (!datamatcher_match(&di->matcher, str)) continue; } else { /* stringify filelist if requested */ if (di->keyname == SOLVABLE_FILELIST && di->key->type == REPOKEY_TYPE_DIRSTRARRAY && (di->flags & SEARCH_FILES) != 0) repodata_stringify(di->pool, di->data, di->key, &di->kv, di->flags); } /* found something! */ return 1; } } void dataiterator_entersub(Dataiterator *di) { if (di->state == di_nextarrayelement) di->state = di_entersub; } void dataiterator_setpos(Dataiterator *di) { if (di->kv.eof == 2) { pool_clear_pos(di->pool); return; } di->pool->pos.solvid = di->solvid; di->pool->pos.repo = di->repo; di->pool->pos.repodataid = di->data - di->repo->repodata; di->pool->pos.schema = di->kv.id; di->pool->pos.dp = (unsigned char *)di->kv.str - di->data->incoredata; } void dataiterator_setpos_parent(Dataiterator *di) { if (!di->kv.parent || di->kv.parent->eof == 2) { pool_clear_pos(di->pool); return; } di->pool->pos.solvid = di->solvid; di->pool->pos.repo = di->repo; di->pool->pos.repodataid = di->data - di->repo->repodata; di->pool->pos.schema = di->kv.parent->id; di->pool->pos.dp = (unsigned char *)di->kv.parent->str - di->data->incoredata; } /* clones just the position, not the search keys/matcher */ void dataiterator_clonepos(Dataiterator *di, Dataiterator *from) { di->state = from->state; di->flags &= ~SEARCH_THISSOLVID; di->flags |= (from->flags & SEARCH_THISSOLVID); di->repo = from->repo; di->data = from->data; di->dp = from->dp; di->ddp = from->ddp; di->idp = from->idp; di->keyp = from->keyp; di->key = from->key; di->kv = from->kv; di->repodataid = from->repodataid; di->solvid = from->solvid; di->repoid = from->repoid; di->rootlevel = from->rootlevel; memcpy(di->parents, from->parents, sizeof(from->parents)); di->nparents = from->nparents; if (di->nparents) { int i; for (i = 1; i < di->nparents; i++) di->parents[i].kv.parent = &di->parents[i - 1].kv; di->kv.parent = &di->parents[di->nparents - 1].kv; } di->dupstr = 0; di->dupstrn = 0; if (from->dupstr && from->dupstr == from->kv.str) { di->dupstrn = from->dupstrn; di->dupstr = solv_memdup(from->dupstr, from->dupstrn); } } void dataiterator_seek(Dataiterator *di, int whence) { if ((whence & DI_SEEK_STAY) != 0) di->rootlevel = di->nparents; switch (whence & ~DI_SEEK_STAY) { case DI_SEEK_CHILD: if (di->state != di_nextarrayelement) break; if ((whence & DI_SEEK_STAY) != 0) di->rootlevel = di->nparents + 1; /* XXX: dangerous! */ di->state = di_entersub; break; case DI_SEEK_PARENT: if (!di->nparents) { di->state = di_bye; break; } di->nparents--; if (di->rootlevel > di->nparents) di->rootlevel = di->nparents; di->dp = di->parents[di->nparents].dp; di->kv = di->parents[di->nparents].kv; di->keyp = di->parents[di->nparents].keyp; di->key = di->data->keys + *di->keyp; di->ddp = (unsigned char *)di->kv.str; di->keyname = di->keynames[di->nparents - di->rootlevel]; di->state = di_nextarrayelement; break; case DI_SEEK_REWIND: if (!di->nparents) { di->state = di_bye; break; } di->dp = (unsigned char *)di->kv.parent->str; di->keyp = di->data->schemadata + di->data->schemata[di->kv.parent->id]; di->state = di_enterschema; break; default: break; } } void dataiterator_skip_attribute(Dataiterator *di) { if (di->state == di_nextsolvableattr) di->state = di_nextsolvablekey; else di->state = di_nextkey; } void dataiterator_skip_solvable(Dataiterator *di) { di->nparents = 0; di->kv.parent = 0; di->rootlevel = 0; di->keyname = di->keynames[0]; di->state = di_nextsolvable; } void dataiterator_skip_repo(Dataiterator *di) { di->nparents = 0; di->kv.parent = 0; di->rootlevel = 0; di->keyname = di->keynames[0]; di->state = di_nextrepo; } void dataiterator_jump_to_solvid(Dataiterator *di, Id solvid) { di->nparents = 0; di->kv.parent = 0; di->rootlevel = 0; di->keyname = di->keynames[0]; if (solvid == SOLVID_POS) { di->repo = di->pool->pos.repo; if (!di->repo) { di->state = di_bye; return; } di->repoid = 0; if (!di->pool->pos.repodataid && di->pool->pos.solvid == SOLVID_META) { solvid = SOLVID_META; /* META pos hack */ } else { di->data = di->repo->repodata + di->pool->pos.repodataid; di->repodataid = 0; } } else if (solvid > 0) { di->repo = di->pool->solvables[solvid].repo; di->repoid = 0; } if (di->repoid > 0) { if (!di->pool->urepos) { di->state = di_bye; return; } di->repoid = 1; di->repo = di->pool->repos[di->repoid]; } if (solvid != SOLVID_POS) di->repodataid = 1; di->solvid = solvid; if (solvid) di->flags |= SEARCH_THISSOLVID; di->state = di_enterrepo; } void dataiterator_jump_to_repo(Dataiterator *di, Repo *repo) { di->nparents = 0; di->kv.parent = 0; di->rootlevel = 0; di->repo = repo; di->repoid = 0; /* 0 means stay at repo */ di->repodataid = 1; di->solvid = 0; di->flags &= ~SEARCH_THISSOLVID; di->state = di_enterrepo; } int dataiterator_match(Dataiterator *di, Datamatcher *ma) { const char *str; if (!(str = repodata_stringify(di->pool, di->data, di->key, &di->kv, di->flags))) return 0; return ma ? datamatcher_match(ma, str) : 1; } void dataiterator_strdup(Dataiterator *di) { int l = -1; if (!di->kv.str || di->kv.str == di->dupstr) return; switch (di->key->type) { case_CHKSUM_TYPES: case REPOKEY_TYPE_DIRSTRARRAY: if (di->kv.num) /* was it stringified into tmp space? */ l = strlen(di->kv.str) + 1; break; default: break; } if (l < 0 && di->key->storage == KEY_STORAGE_VERTICAL_OFFSET) { switch (di->key->type) { case REPOKEY_TYPE_STR: case REPOKEY_TYPE_DIRSTRARRAY: l = strlen(di->kv.str) + 1; break; case_CHKSUM_TYPES: l = solv_chksum_len(di->key->type); break; case REPOKEY_TYPE_BINARY: l = di->kv.num; break; } } if (l >= 0) { if (!di->dupstrn || di->dupstrn < l) { di->dupstrn = l + 16; di->dupstr = solv_realloc(di->dupstr, di->dupstrn); } if (l) memcpy(di->dupstr, di->kv.str, l); di->kv.str = di->dupstr; } } /************************************************************************ * data modify functions */ /* extend repodata so that it includes solvables p */ void repodata_extend(Repodata *data, Id p) { if (data->start == data->end) data->start = data->end = p; if (p >= data->end) { int old = data->end - data->start; int new = p - data->end + 1; if (data->attrs) { data->attrs = solv_extend(data->attrs, old, new, sizeof(Id *), REPODATA_BLOCK); memset(data->attrs + old, 0, new * sizeof(Id *)); } data->incoreoffset = solv_extend(data->incoreoffset, old, new, sizeof(Id), REPODATA_BLOCK); memset(data->incoreoffset + old, 0, new * sizeof(Id)); data->end = p + 1; } if (p < data->start) { int old = data->end - data->start; int new = data->start - p; if (data->attrs) { data->attrs = solv_extend_resize(data->attrs, old + new, sizeof(Id *), REPODATA_BLOCK); memmove(data->attrs + new, data->attrs, old * sizeof(Id *)); memset(data->attrs, 0, new * sizeof(Id *)); } data->incoreoffset = solv_extend_resize(data->incoreoffset, old + new, sizeof(Id), REPODATA_BLOCK); memmove(data->incoreoffset + new, data->incoreoffset, old * sizeof(Id)); memset(data->incoreoffset, 0, new * sizeof(Id)); data->start = p; } } /* shrink end of repodata */ void repodata_shrink(Repodata *data, int end) { int i; if (data->end <= end) return; if (data->start >= end) { if (data->attrs) { for (i = 0; i < data->end - data->start; i++) solv_free(data->attrs[i]); data->attrs = solv_free(data->attrs); } data->incoreoffset = solv_free(data->incoreoffset); data->start = data->end = 0; return; } if (data->attrs) { for (i = end; i < data->end; i++) solv_free(data->attrs[i - data->start]); data->attrs = solv_extend_resize(data->attrs, end - data->start, sizeof(Id *), REPODATA_BLOCK); } if (data->incoreoffset) data->incoreoffset = solv_extend_resize(data->incoreoffset, end - data->start, sizeof(Id), REPODATA_BLOCK); data->end = end; } /* extend repodata so that it includes solvables from start to start + num - 1 */ void repodata_extend_block(Repodata *data, Id start, Id num) { if (!num) return; if (!data->incoreoffset) { /* this also means that data->attrs is NULL */ data->incoreoffset = solv_calloc_block(num, sizeof(Id), REPODATA_BLOCK); data->start = start; data->end = start + num; return; } repodata_extend(data, start); if (num > 1) repodata_extend(data, start + num - 1); } /**********************************************************************/ #define REPODATA_ATTRS_BLOCK 31 #define REPODATA_ATTRDATA_BLOCK 1023 #define REPODATA_ATTRIDDATA_BLOCK 63 #define REPODATA_ATTRNUM64DATA_BLOCK 15 Id repodata_new_handle(Repodata *data) { if (!data->nxattrs) { data->xattrs = solv_calloc_block(1, sizeof(Id *), REPODATA_BLOCK); data->nxattrs = 2; /* -1: SOLVID_META */ } data->xattrs = solv_extend(data->xattrs, data->nxattrs, 1, sizeof(Id *), REPODATA_BLOCK); data->xattrs[data->nxattrs] = 0; return -(data->nxattrs++); } static inline Id ** repodata_get_attrp(Repodata *data, Id handle) { if (handle < 0) { if (handle == SOLVID_META && !data->xattrs) { data->xattrs = solv_calloc_block(1, sizeof(Id *), REPODATA_BLOCK); data->nxattrs = 2; } return data->xattrs - handle; } if (handle < data->start || handle >= data->end) repodata_extend(data, handle); if (!data->attrs) data->attrs = solv_calloc_block(data->end - data->start, sizeof(Id *), REPODATA_BLOCK); return data->attrs + (handle - data->start); } static void repodata_insert_keyid(Repodata *data, Id handle, Id keyid, Id val, int overwrite) { Id *pp; Id *ap, **app; int i; app = repodata_get_attrp(data, handle); ap = *app; i = 0; if (ap) { /* Determine equality based on the name only, allows us to change type (when overwrite is set), and makes TYPE_CONSTANT work. */ for (pp = ap; *pp; pp += 2) if (data->keys[*pp].name == data->keys[keyid].name) break; if (*pp) { if (overwrite || data->keys[*pp].type == REPOKEY_TYPE_DELETED) { pp[0] = keyid; pp[1] = val; } return; } i = pp - ap; } ap = solv_extend(ap, i, 3, sizeof(Id), REPODATA_ATTRS_BLOCK); *app = ap; pp = ap + i; *pp++ = keyid; *pp++ = val; *pp = 0; } static void repodata_set(Repodata *data, Id solvid, Repokey *key, Id val) { Id keyid; keyid = repodata_key2id(data, key, 1); repodata_insert_keyid(data, solvid, keyid, val, 1); } void repodata_set_id(Repodata *data, Id solvid, Id keyname, Id id) { Repokey key; key.name = keyname; key.type = REPOKEY_TYPE_ID; key.size = 0; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, id); } void repodata_set_num(Repodata *data, Id solvid, Id keyname, unsigned long long num) { Repokey key; key.name = keyname; key.type = REPOKEY_TYPE_NUM; key.size = 0; key.storage = KEY_STORAGE_INCORE; if (num >= 0x80000000) { data->attrnum64data = solv_extend(data->attrnum64data, data->attrnum64datalen, 1, sizeof(unsigned long long), REPODATA_ATTRNUM64DATA_BLOCK); data->attrnum64data[data->attrnum64datalen] = num; num = 0x80000000 | data->attrnum64datalen++; } repodata_set(data, solvid, &key, (Id)num); } void repodata_set_poolstr(Repodata *data, Id solvid, Id keyname, const char *str) { Repokey key; Id id; if (data->localpool) id = stringpool_str2id(&data->spool, str, 1); else id = pool_str2id(data->repo->pool, str, 1); key.name = keyname; key.type = REPOKEY_TYPE_ID; key.size = 0; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, id); } void repodata_set_constant(Repodata *data, Id solvid, Id keyname, unsigned int constant) { Repokey key; key.name = keyname; key.type = REPOKEY_TYPE_CONSTANT; key.size = constant; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, 0); } void repodata_set_constantid(Repodata *data, Id solvid, Id keyname, Id id) { Repokey key; key.name = keyname; key.type = REPOKEY_TYPE_CONSTANTID; key.size = id; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, 0); } void repodata_set_void(Repodata *data, Id solvid, Id keyname) { Repokey key; key.name = keyname; key.type = REPOKEY_TYPE_VOID; key.size = 0; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, 0); } void repodata_set_str(Repodata *data, Id solvid, Id keyname, const char *str) { Repokey key; int l; l = strlen(str) + 1; key.name = keyname; key.type = REPOKEY_TYPE_STR; key.size = 0; key.storage = KEY_STORAGE_INCORE; data->attrdata = solv_extend(data->attrdata, data->attrdatalen, l, 1, REPODATA_ATTRDATA_BLOCK); memcpy(data->attrdata + data->attrdatalen, str, l); repodata_set(data, solvid, &key, data->attrdatalen); data->attrdatalen += l; } void repodata_set_binary(Repodata *data, Id solvid, Id keyname, void *buf, int len) { Repokey key; unsigned char *dp; if (len < 0) return; key.name = keyname; key.type = REPOKEY_TYPE_BINARY; key.size = 0; key.storage = KEY_STORAGE_INCORE; data->attrdata = solv_extend(data->attrdata, data->attrdatalen, len + 5, 1, REPODATA_ATTRDATA_BLOCK); dp = data->attrdata + data->attrdatalen; if (len >= (1 << 14)) { if (len >= (1 << 28)) *dp++ = (len >> 28) | 128; if (len >= (1 << 21)) *dp++ = (len >> 21) | 128; *dp++ = (len >> 14) | 128; } if (len >= (1 << 7)) *dp++ = (len >> 7) | 128; *dp++ = len & 127; if (len) memcpy(dp, buf, len); repodata_set(data, solvid, &key, data->attrdatalen); data->attrdatalen = dp + len - data->attrdata; } /* add an array element consisting of entrysize Ids to the repodata. modifies attriddata * so that the caller can append entrysize new elements plus the termination zero there */ static void repodata_add_array(Repodata *data, Id handle, Id keyname, Id keytype, int entrysize) { int oldsize; Id *ida, *pp, **ppp; /* check if it is the same as last time, this speeds things up a lot */ if (handle == data->lasthandle && data->keys[data->lastkey].name == keyname && data->keys[data->lastkey].type == keytype && data->attriddatalen == data->lastdatalen) { /* great! just append the new data */ data->attriddata = solv_extend(data->attriddata, data->attriddatalen, entrysize, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK); data->attriddatalen--; /* overwrite terminating 0 */ data->lastdatalen += entrysize; return; } ppp = repodata_get_attrp(data, handle); pp = *ppp; if (pp) { for (; *pp; pp += 2) if (data->keys[*pp].name == keyname) break; } if (!pp || !*pp || data->keys[*pp].type != keytype) { /* not found. allocate new key */ Repokey key; Id keyid; key.name = keyname; key.type = keytype; key.size = 0; key.storage = KEY_STORAGE_INCORE; data->attriddata = solv_extend(data->attriddata, data->attriddatalen, entrysize + 1, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK); keyid = repodata_key2id(data, &key, 1); repodata_insert_keyid(data, handle, keyid, data->attriddatalen, 1); data->lasthandle = handle; data->lastkey = keyid; data->lastdatalen = data->attriddatalen + entrysize + 1; return; } oldsize = 0; for (ida = data->attriddata + pp[1]; *ida; ida += entrysize) oldsize += entrysize; if (ida + 1 == data->attriddata + data->attriddatalen) { /* this was the last entry, just append it */ data->attriddata = solv_extend(data->attriddata, data->attriddatalen, entrysize, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK); data->attriddatalen--; /* overwrite terminating 0 */ } else { /* too bad. move to back. */ data->attriddata = solv_extend(data->attriddata, data->attriddatalen, oldsize + entrysize + 1, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK); memcpy(data->attriddata + data->attriddatalen, data->attriddata + pp[1], oldsize * sizeof(Id)); pp[1] = data->attriddatalen; data->attriddatalen += oldsize; } data->lasthandle = handle; data->lastkey = *pp; data->lastdatalen = data->attriddatalen + entrysize + 1; } void repodata_set_bin_checksum(Repodata *data, Id solvid, Id keyname, Id type, const unsigned char *str) { Repokey key; int l; if (!(l = solv_chksum_len(type))) return; key.name = keyname; key.type = type; key.size = 0; key.storage = KEY_STORAGE_INCORE; data->attrdata = solv_extend(data->attrdata, data->attrdatalen, l, 1, REPODATA_ATTRDATA_BLOCK); memcpy(data->attrdata + data->attrdatalen, str, l); repodata_set(data, solvid, &key, data->attrdatalen); data->attrdatalen += l; } void repodata_set_checksum(Repodata *data, Id solvid, Id keyname, Id type, const char *str) { unsigned char buf[64]; int l; if (!(l = solv_chksum_len(type))) return; if (l > sizeof(buf) || solv_hex2bin(&str, buf, l) != l) return; repodata_set_bin_checksum(data, solvid, keyname, type, buf); } const char * repodata_chk2str(Repodata *data, Id type, const unsigned char *buf) { int l; if (!(l = solv_chksum_len(type))) return ""; return pool_bin2hex(data->repo->pool, buf, l); } /* rpm filenames don't contain the epoch, so strip it */ static inline const char * evrid2vrstr(Pool *pool, Id evrid) { const char *p, *evr = pool_id2str(pool, evrid); if (!evr) return evr; for (p = evr; *p >= '0' && *p <= '9'; p++) ; return p != evr && *p == ':' && p[1] ? p + 1 : evr; } static inline void repodata_set_poolstrn(Repodata *data, Id solvid, Id keyname, const char *str, int l) { Id id; if (data->localpool) id = stringpool_strn2id(&data->spool, str, l, 1); else id = pool_strn2id(data->repo->pool, str, l, 1); repodata_set_id(data, solvid, keyname, id); } static inline void repodata_set_strn(Repodata *data, Id solvid, Id keyname, const char *str, int l) { if (!str[l]) repodata_set_str(data, solvid, keyname, str); else { char *s = solv_strdup(str); s[l] = 0; repodata_set_str(data, solvid, keyname, s); free(s); } } void repodata_set_location(Repodata *data, Id solvid, int medianr, const char *dir, const char *file) { Pool *pool = data->repo->pool; Solvable *s; const char *str, *fp; int l = 0; if (medianr) repodata_set_constant(data, solvid, SOLVABLE_MEDIANR, medianr); if (!dir) { if ((dir = strrchr(file, '/')) != 0) { l = dir - file; dir = file; file = dir + l + 1; if (!l) l++; } } else l = strlen(dir); if (l >= 2 && dir[0] == '.' && dir[1] == '/' && (l == 2 || dir[2] != '/')) { dir += 2; l -= 2; } if (l == 1 && dir[0] == '.') l = 0; s = pool->solvables + solvid; if (dir && l) { str = pool_id2str(pool, s->arch); if (!strncmp(dir, str, l) && !str[l]) repodata_set_void(data, solvid, SOLVABLE_MEDIADIR); else repodata_set_strn(data, solvid, SOLVABLE_MEDIADIR, dir, l); } fp = file; str = pool_id2str(pool, s->name); l = strlen(str); if ((!l || !strncmp(fp, str, l)) && fp[l] == '-') { fp += l + 1; str = evrid2vrstr(pool, s->evr); l = strlen(str); if ((!l || !strncmp(fp, str, l)) && fp[l] == '.') { fp += l + 1; str = pool_id2str(pool, s->arch); l = strlen(str); if ((!l || !strncmp(fp, str, l)) && !strcmp(fp + l, ".rpm")) { repodata_set_void(data, solvid, SOLVABLE_MEDIAFILE); return; } } } repodata_set_str(data, solvid, SOLVABLE_MEDIAFILE, file); } /* XXX: medianr is currently not stored */ void repodata_set_deltalocation(Repodata *data, Id handle, int medianr, const char *dir, const char *file) { int l = 0; const char *evr, *suf, *s; if (!dir) { if ((dir = strrchr(file, '/')) != 0) { l = dir - file; dir = file; file = dir + l + 1; if (!l) l++; } } else l = strlen(dir); if (l >= 2 && dir[0] == '.' && dir[1] == '/' && (l == 2 || dir[2] != '/')) { dir += 2; l -= 2; } if (l == 1 && dir[0] == '.') l = 0; if (dir && l) repodata_set_poolstrn(data, handle, DELTA_LOCATION_DIR, dir, l); evr = strchr(file, '-'); if (evr) { for (s = evr - 1; s > file; s--) if (*s == '-') { evr = s; break; } } suf = strrchr(file, '.'); if (suf) { for (s = suf - 1; s > file; s--) if (*s == '.') { suf = s; break; } if (!strcmp(suf, ".delta.rpm") || !strcmp(suf, ".patch.rpm")) { /* We accept one more item as suffix. */ for (s = suf - 1; s > file; s--) if (*s == '.') { suf = s; break; } } } if (!evr) suf = 0; if (suf && evr && suf < evr) suf = 0; repodata_set_poolstrn(data, handle, DELTA_LOCATION_NAME, file, evr ? evr - file : strlen(file)); if (evr) repodata_set_poolstrn(data, handle, DELTA_LOCATION_EVR, evr + 1, suf ? suf - evr - 1: strlen(evr + 1)); if (suf) repodata_set_poolstr(data, handle, DELTA_LOCATION_SUFFIX, suf + 1); } void repodata_set_sourcepkg(Repodata *data, Id solvid, const char *sourcepkg) { Pool *pool = data->repo->pool; Solvable *s = pool->solvables + solvid; const char *p, *sevr, *sarch, *name, *evr; p = strrchr(sourcepkg, '.'); if (!p || strcmp(p, ".rpm") != 0) { if (*sourcepkg) repodata_set_str(data, solvid, SOLVABLE_SOURCENAME, sourcepkg); return; } p--; while (p > sourcepkg && *p != '.') p--; if (*p != '.' || p == sourcepkg) return; sarch = p-- + 1; while (p > sourcepkg && *p != '-') p--; if (*p != '-' || p == sourcepkg) return; p--; while (p > sourcepkg && *p != '-') p--; if (*p != '-' || p == sourcepkg) return; sevr = p + 1; pool = s->repo->pool; name = pool_id2str(pool, s->name); if (name && !strncmp(sourcepkg, name, sevr - sourcepkg - 1) && name[sevr - sourcepkg - 1] == 0) repodata_set_void(data, solvid, SOLVABLE_SOURCENAME); else repodata_set_id(data, solvid, SOLVABLE_SOURCENAME, pool_strn2id(pool, sourcepkg, sevr - sourcepkg - 1, 1)); evr = evrid2vrstr(pool, s->evr); if (evr && !strncmp(sevr, evr, sarch - sevr - 1) && evr[sarch - sevr - 1] == 0) repodata_set_void(data, solvid, SOLVABLE_SOURCEEVR); else repodata_set_id(data, solvid, SOLVABLE_SOURCEEVR, pool_strn2id(pool, sevr, sarch - sevr - 1, 1)); if (!strcmp(sarch, "src.rpm")) repodata_set_constantid(data, solvid, SOLVABLE_SOURCEARCH, ARCH_SRC); else if (!strcmp(sarch, "nosrc.rpm")) repodata_set_constantid(data, solvid, SOLVABLE_SOURCEARCH, ARCH_NOSRC); else repodata_set_constantid(data, solvid, SOLVABLE_SOURCEARCH, pool_strn2id(pool, sarch, strlen(sarch) - 4, 1)); } void repodata_set_idarray(Repodata *data, Id solvid, Id keyname, Queue *q) { Repokey key; int i; key.name = keyname; key.type = REPOKEY_TYPE_IDARRAY; key.size = 0; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, data->attriddatalen); data->attriddata = solv_extend(data->attriddata, data->attriddatalen, q->count + 1, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK); for (i = 0; i < q->count; i++) data->attriddata[data->attriddatalen++] = q->elements[i]; data->attriddata[data->attriddatalen++] = 0; } void repodata_add_dirnumnum(Repodata *data, Id solvid, Id keyname, Id dir, Id num, Id num2) { assert(dir); #if 0 fprintf(stderr, "repodata_add_dirnumnum %d %d %d %d (%d)\n", solvid, dir, num, num2, data->attriddatalen); #endif repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_DIRNUMNUMARRAY, 3); data->attriddata[data->attriddatalen++] = dir; data->attriddata[data->attriddatalen++] = num; data->attriddata[data->attriddatalen++] = num2; data->attriddata[data->attriddatalen++] = 0; } void repodata_add_dirstr(Repodata *data, Id solvid, Id keyname, Id dir, const char *str) { Id stroff; int l; assert(dir); l = strlen(str) + 1; data->attrdata = solv_extend(data->attrdata, data->attrdatalen, l, 1, REPODATA_ATTRDATA_BLOCK); memcpy(data->attrdata + data->attrdatalen, str, l); stroff = data->attrdatalen; data->attrdatalen += l; #if 0 fprintf(stderr, "repodata_add_dirstr %d %d %s (%d)\n", solvid, dir, str, data->attriddatalen); #endif repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_DIRSTRARRAY, 2); data->attriddata[data->attriddatalen++] = dir; data->attriddata[data->attriddatalen++] = stroff; data->attriddata[data->attriddatalen++] = 0; } void repodata_add_idarray(Repodata *data, Id solvid, Id keyname, Id id) { #if 0 fprintf(stderr, "repodata_add_idarray %d %d (%d)\n", solvid, id, data->attriddatalen); #endif repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_IDARRAY, 1); data->attriddata[data->attriddatalen++] = id; data->attriddata[data->attriddatalen++] = 0; } void repodata_add_poolstr_array(Repodata *data, Id solvid, Id keyname, const char *str) { Id id; if (data->localpool) id = stringpool_str2id(&data->spool, str, 1); else id = pool_str2id(data->repo->pool, str, 1); repodata_add_idarray(data, solvid, keyname, id); } void repodata_add_fixarray(Repodata *data, Id solvid, Id keyname, Id handle) { repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_FIXARRAY, 1); data->attriddata[data->attriddatalen++] = handle; data->attriddata[data->attriddatalen++] = 0; } void repodata_add_flexarray(Repodata *data, Id solvid, Id keyname, Id handle) { repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_FLEXARRAY, 1); data->attriddata[data->attriddatalen++] = handle; data->attriddata[data->attriddatalen++] = 0; } void repodata_set_kv(Repodata *data, Id solvid, Id keyname, Id keytype, KeyValue *kv) { switch (keytype) { case REPOKEY_TYPE_ID: repodata_set_id(data, solvid, keyname, kv->id); break; case REPOKEY_TYPE_CONSTANTID: repodata_set_constantid(data, solvid, keyname, kv->id); break; case REPOKEY_TYPE_IDARRAY: repodata_add_idarray(data, solvid, keyname, kv->id); break; case REPOKEY_TYPE_STR: repodata_set_str(data, solvid, keyname, kv->str); break; case REPOKEY_TYPE_VOID: repodata_set_void(data, solvid, keyname); break; case REPOKEY_TYPE_NUM: repodata_set_num(data, solvid, keyname, SOLV_KV_NUM64(kv)); break; case REPOKEY_TYPE_CONSTANT: repodata_set_constant(data, solvid, keyname, kv->num); break; case REPOKEY_TYPE_DIRNUMNUMARRAY: if (kv->id) repodata_add_dirnumnum(data, solvid, keyname, kv->id, kv->num, kv->num2); break; case REPOKEY_TYPE_DIRSTRARRAY: repodata_add_dirstr(data, solvid, keyname, kv->id, kv->str); break; case_CHKSUM_TYPES: repodata_set_bin_checksum(data, solvid, keyname, keytype, (const unsigned char *)kv->str); break; default: break; } } void repodata_unset_uninternalized(Repodata *data, Id solvid, Id keyname) { Id *pp, *ap, **app; app = repodata_get_attrp(data, solvid); ap = *app; if (!ap) return; if (!keyname) { *app = 0; /* delete all attributes */ return; } for (; *ap; ap += 2) if (data->keys[*ap].name == keyname) break; if (!*ap) return; pp = ap; ap += 2; for (; *ap; ap += 2) { if (data->keys[*ap].name == keyname) continue; *pp++ = ap[0]; *pp++ = ap[1]; } *pp = 0; } void repodata_unset(Repodata *data, Id solvid, Id keyname) { Repokey key; key.name = keyname; key.type = REPOKEY_TYPE_DELETED; key.size = 0; key.storage = KEY_STORAGE_INCORE; repodata_set(data, solvid, &key, 0); } /* add all (uninternalized) attrs from src to dest */ void repodata_merge_attrs(Repodata *data, Id dest, Id src) { Id *keyp; if (dest == src || !data->attrs || !(keyp = data->attrs[src - data->start])) return; for (; *keyp; keyp += 2) repodata_insert_keyid(data, dest, keyp[0], keyp[1], 0); } /* add some (uninternalized) attrs from src to dest */ void repodata_merge_some_attrs(Repodata *data, Id dest, Id src, Map *keyidmap, int overwrite) { Id *keyp; if (dest == src || !data->attrs || !(keyp = data->attrs[src - data->start])) return; for (; *keyp; keyp += 2) if (!keyidmap || MAPTST(keyidmap, keyp[0])) repodata_insert_keyid(data, dest, keyp[0], keyp[1], overwrite); } /* swap (uninternalized) attrs from src and dest */ void repodata_swap_attrs(Repodata *data, Id dest, Id src) { Id *tmpattrs; if (!data->attrs || dest == src) return; if (dest < data->start || dest >= data->end) repodata_extend(data, dest); if (src < data->start || src >= data->end) repodata_extend(data, src); tmpattrs = data->attrs[dest - data->start]; data->attrs[dest - data->start] = data->attrs[src - data->start]; data->attrs[src - data->start] = tmpattrs; } /**********************************************************************/ /* TODO: unify with repo_write and repo_solv! */ #define EXTDATA_BLOCK 1023 struct extdata { unsigned char *buf; int len; }; static void data_addid(struct extdata *xd, Id sx) { unsigned int x = (unsigned int)sx; unsigned char *dp; xd->buf = solv_extend(xd->buf, xd->len, 5, 1, EXTDATA_BLOCK); dp = xd->buf + xd->len; if (x >= (1 << 14)) { if (x >= (1 << 28)) *dp++ = (x >> 28) | 128; if (x >= (1 << 21)) *dp++ = (x >> 21) | 128; *dp++ = (x >> 14) | 128; } if (x >= (1 << 7)) *dp++ = (x >> 7) | 128; *dp++ = x & 127; xd->len = dp - xd->buf; } static void data_addid64(struct extdata *xd, unsigned long long x) { if (x >= 0x100000000) { if ((x >> 35) != 0) { data_addid(xd, (Id)(x >> 35)); xd->buf[xd->len - 1] |= 128; } data_addid(xd, (Id)((unsigned int)x | 0x80000000)); xd->buf[xd->len - 5] = (x >> 28) | 128; } else data_addid(xd, (Id)x); } static void data_addideof(struct extdata *xd, Id sx, int eof) { unsigned int x = (unsigned int)sx; unsigned char *dp; xd->buf = solv_extend(xd->buf, xd->len, 5, 1, EXTDATA_BLOCK); dp = xd->buf + xd->len; if (x >= (1 << 13)) { if (x >= (1 << 27)) *dp++ = (x >> 27) | 128; if (x >= (1 << 20)) *dp++ = (x >> 20) | 128; *dp++ = (x >> 13) | 128; } if (x >= (1 << 6)) *dp++ = (x >> 6) | 128; *dp++ = eof ? (x & 63) : (x & 63) | 64; xd->len = dp - xd->buf; } static void data_addblob(struct extdata *xd, unsigned char *blob, int len) { xd->buf = solv_extend(xd->buf, xd->len, len, 1, EXTDATA_BLOCK); memcpy(xd->buf + xd->len, blob, len); xd->len += len; } /*********************************/ /* this is to reduct memory usage when internalizing oversized repos */ static void compact_attrdata(Repodata *data, int entry, int nentry) { int i; unsigned int attrdatastart = data->attrdatalen; unsigned int attriddatastart = data->attriddatalen; if (attrdatastart < 1024 * 1024 * 4 && attriddatastart < 1024 * 1024) return; for (i = entry; i < nentry; i++) { Id v, *attrs = data->attrs[i]; if (!attrs) continue; for (; *attrs; attrs += 2) { switch (data->keys[*attrs].type) { case REPOKEY_TYPE_STR: case REPOKEY_TYPE_BINARY: case_CHKSUM_TYPES: if ((unsigned int)attrs[1] < attrdatastart) attrdatastart = attrs[1]; break; case REPOKEY_TYPE_DIRSTRARRAY: for (v = attrs[1]; data->attriddata[v] ; v += 2) if ((unsigned int)data->attriddata[v + 1] < attrdatastart) attrdatastart = data->attriddata[v + 1]; /* FALLTHROUGH */ case REPOKEY_TYPE_IDARRAY: case REPOKEY_TYPE_DIRNUMNUMARRAY: if ((unsigned int)attrs[1] < attriddatastart) attriddatastart = attrs[1]; break; case REPOKEY_TYPE_FIXARRAY: case REPOKEY_TYPE_FLEXARRAY: return; default: break; } } } #if 0 printf("compact_attrdata %d %d\n", entry, nentry); printf("attrdatastart: %d\n", attrdatastart); printf("attriddatastart: %d\n", attriddatastart); #endif if (attrdatastart < 1024 * 1024 * 4 && attriddatastart < 1024 * 1024) return; for (i = entry; i < nentry; i++) { Id v, *attrs = data->attrs[i]; if (!attrs) continue; for (; *attrs; attrs += 2) { switch (data->keys[*attrs].type) { case REPOKEY_TYPE_STR: case REPOKEY_TYPE_BINARY: case_CHKSUM_TYPES: attrs[1] -= attrdatastart; break; case REPOKEY_TYPE_DIRSTRARRAY: for (v = attrs[1]; data->attriddata[v] ; v += 2) data->attriddata[v + 1] -= attrdatastart; /* FALLTHROUGH */ case REPOKEY_TYPE_IDARRAY: case REPOKEY_TYPE_DIRNUMNUMARRAY: attrs[1] -= attriddatastart; break; default: break; } } } if (attrdatastart) { data->attrdatalen -= attrdatastart; memmove(data->attrdata, data->attrdata + attrdatastart, data->attrdatalen); data->attrdata = solv_extend_resize(data->attrdata, data->attrdatalen, 1, REPODATA_ATTRDATA_BLOCK); } if (attriddatastart) { data->attriddatalen -= attriddatastart; memmove(data->attriddata, data->attriddata + attriddatastart, data->attriddatalen * sizeof(Id)); data->attriddata = solv_extend_resize(data->attriddata, data->attriddatalen, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK); } } /* internalalize some key into incore/vincore data */ static void repodata_serialize_key(Repodata *data, struct extdata *newincore, struct extdata *newvincore, Id *schema, Repokey *key, Id val) { Id *ida; struct extdata *xd; unsigned int oldvincorelen = 0; Id schemaid, *sp; xd = newincore; if (key->storage == KEY_STORAGE_VERTICAL_OFFSET) { xd = newvincore; oldvincorelen = xd->len; } switch (key->type) { case REPOKEY_TYPE_VOID: case REPOKEY_TYPE_CONSTANT: case REPOKEY_TYPE_CONSTANTID: case REPOKEY_TYPE_DELETED: break; case REPOKEY_TYPE_STR: data_addblob(xd, data->attrdata + val, strlen((char *)(data->attrdata + val)) + 1); break; case REPOKEY_TYPE_MD5: data_addblob(xd, data->attrdata + val, SIZEOF_MD5); break; case REPOKEY_TYPE_SHA1: data_addblob(xd, data->attrdata + val, SIZEOF_SHA1); break; case REPOKEY_TYPE_SHA224: data_addblob(xd, data->attrdata + val, SIZEOF_SHA224); break; case REPOKEY_TYPE_SHA256: data_addblob(xd, data->attrdata + val, SIZEOF_SHA256); break; case REPOKEY_TYPE_SHA384: data_addblob(xd, data->attrdata + val, SIZEOF_SHA384); break; case REPOKEY_TYPE_SHA512: data_addblob(xd, data->attrdata + val, SIZEOF_SHA512); break; case REPOKEY_TYPE_NUM: if (val & 0x80000000) { data_addid64(xd, data->attrnum64data[val ^ 0x80000000]); break; } /* FALLTHROUGH */ case REPOKEY_TYPE_ID: case REPOKEY_TYPE_DIR: data_addid(xd, val); break; case REPOKEY_TYPE_BINARY: { Id len; unsigned char *dp = data_read_id(data->attrdata + val, &len); dp += (unsigned int)len; data_addblob(xd, data->attrdata + val, dp - (data->attrdata + val)); } break; case REPOKEY_TYPE_IDARRAY: for (ida = data->attriddata + val; *ida; ida++) data_addideof(xd, ida[0], ida[1] ? 0 : 1); break; case REPOKEY_TYPE_DIRNUMNUMARRAY: for (ida = data->attriddata + val; *ida; ida += 3) { data_addid(xd, ida[0]); data_addid(xd, ida[1]); data_addideof(xd, ida[2], ida[3] ? 0 : 1); } break; case REPOKEY_TYPE_DIRSTRARRAY: for (ida = data->attriddata + val; *ida; ida += 2) { data_addideof(xd, ida[0], ida[2] ? 0 : 1); data_addblob(xd, data->attrdata + ida[1], strlen((char *)(data->attrdata + ida[1])) + 1); } break; case REPOKEY_TYPE_FIXARRAY: { int num = 0; schemaid = 0; for (ida = data->attriddata + val; *ida; ida++) { Id *kp; sp = schema; kp = data->xattrs[-*ida]; if (!kp) continue; /* ignore empty elements */ num++; for (; *kp; kp += 2) *sp++ = *kp; *sp = 0; if (!schemaid) schemaid = repodata_schema2id(data, schema, 1); else if (schemaid != repodata_schema2id(data, schema, 0)) { pool_debug(data->repo->pool, SOLV_ERROR, "repodata_serialize_key: fixarray substructs with different schemas\n"); num = 0; break; } } data_addid(xd, num); if (!num) break; data_addid(xd, schemaid); for (ida = data->attriddata + val; *ida; ida++) { Id *kp = data->xattrs[-*ida]; if (!kp) continue; for (; *kp; kp += 2) repodata_serialize_key(data, newincore, newvincore, schema, data->keys + *kp, kp[1]); } break; } case REPOKEY_TYPE_FLEXARRAY: { int num = 0; for (ida = data->attriddata + val; *ida; ida++) num++; data_addid(xd, num); for (ida = data->attriddata + val; *ida; ida++) { Id *kp = data->xattrs[-*ida]; if (!kp) { data_addid(xd, 0); /* XXX */ continue; } sp = schema; for (;*kp; kp += 2) *sp++ = *kp; *sp = 0; schemaid = repodata_schema2id(data, schema, 1); data_addid(xd, schemaid); kp = data->xattrs[-*ida]; for (;*kp; kp += 2) repodata_serialize_key(data, newincore, newvincore, schema, data->keys + *kp, kp[1]); } break; } default: pool_debug(data->repo->pool, SOLV_FATAL, "repodata_serialize_key: don't know how to handle type %d\n", key->type); exit(1); } if (key->storage == KEY_STORAGE_VERTICAL_OFFSET) { /* put offset/len in incore */ data_addid(newincore, data->lastverticaloffset + oldvincorelen); oldvincorelen = xd->len - oldvincorelen; data_addid(newincore, oldvincorelen); } } /* create a circular linked list of all keys that share * the same keyname */ static Id * calculate_keylink(Repodata *data) { int i, j; Id *link; Id maxkeyname = 0, *keytable = 0; link = solv_calloc(data->nkeys, sizeof(Id)); if (data->nkeys <= 2) return link; for (i = 1; i < data->nkeys; i++) { Id n = data->keys[i].name; if (n >= maxkeyname) { keytable = solv_realloc2(keytable, n + 128, sizeof(Id)); memset(keytable + maxkeyname, 0, (n + 128 - maxkeyname) * sizeof(Id)); maxkeyname = n + 128; } j = keytable[n]; if (j) link[i] = link[j]; else j = i; link[j] = i; keytable[n] = i; } /* remove links that just point to themselfs */ for (i = 1; i < data->nkeys; i++) if (link[i] == i) link[i] = 0; solv_free(keytable); return link; } void repodata_internalize(Repodata *data) { Repokey *key, solvkey; Id entry, nentry; Id schemaid, keyid, *schema, *sp, oldschemaid, *keyp, *seen; Offset *oldincoreoffs = 0; int schemaidx; unsigned char *dp, *ndp; int neednewschema; struct extdata newincore; struct extdata newvincore; Id solvkeyid; Id *keylink; int haveoldkl; if (!data->attrs && !data->xattrs) return; #if 0 printf("repodata_internalize %d\n", data->repodataid); printf(" attr data: %d K\n", data->attrdatalen / 1024); printf(" attrid data: %d K\n", data->attriddatalen / (1024 / 4)); #endif newvincore.buf = data->vincore; newvincore.len = data->vincorelen; /* find the solvables key, create if needed */ memset(&solvkey, 0, sizeof(solvkey)); solvkey.name = REPOSITORY_SOLVABLES; solvkey.type = REPOKEY_TYPE_FLEXARRAY; solvkey.size = 0; solvkey.storage = KEY_STORAGE_INCORE; solvkeyid = repodata_key2id(data, &solvkey, data->end != data->start ? 1 : 0); schema = solv_malloc2(data->nkeys, sizeof(Id)); seen = solv_malloc2(data->nkeys, sizeof(Id)); /* Merge the data already existing (in data->schemata, ->incoredata and friends) with the new attributes in data->attrs[]. */ nentry = data->end - data->start; memset(&newincore, 0, sizeof(newincore)); data_addid(&newincore, 0); /* start data at offset 1 */ data->mainschema = 0; data->mainschemaoffsets = solv_free(data->mainschemaoffsets); keylink = calculate_keylink(data); /* join entry data */ /* we start with the meta data, entry -1 */ for (entry = -1; entry < nentry; entry++) { oldschemaid = 0; dp = data->incoredata; if (dp) { dp += entry >= 0 ? data->incoreoffset[entry] : 1; dp = data_read_id(dp, &oldschemaid); } memset(seen, 0, data->nkeys * sizeof(Id)); #if 0 fprintf(stderr, "oldschemaid %d\n", oldschemaid); fprintf(stderr, "schemata %d\n", data->schemata[oldschemaid]); fprintf(stderr, "schemadata %p\n", data->schemadata); #endif /* seen: -1: old data, 0: skipped, >0: id + 1 */ neednewschema = 0; sp = schema; haveoldkl = 0; for (keyp = data->schemadata + data->schemata[oldschemaid]; *keyp; keyp++) { if (seen[*keyp]) { /* oops, should not happen */ neednewschema = 1; continue; } seen[*keyp] = -1; /* use old marker */ *sp++ = *keyp; if (keylink[*keyp]) haveoldkl = 1; /* potential keylink conflict */ } /* strip solvables key */ if (entry < 0 && solvkeyid && seen[solvkeyid]) { *sp = 0; for (sp = keyp = schema; *sp; sp++) if (*sp != solvkeyid) *keyp++ = *sp; sp = keyp; seen[solvkeyid] = 0; neednewschema = 1; } /* add new entries */ if (entry >= 0) keyp = data->attrs ? data->attrs[entry] : 0; else keyp = data->xattrs ? data->xattrs[1] : 0; if (keyp) for (; *keyp; keyp += 2) { if (!seen[*keyp]) { neednewschema = 1; *sp++ = *keyp; if (haveoldkl && keylink[*keyp]) /* this should be pretty rare */ { Id kl; for (kl = keylink[*keyp]; kl != *keyp; kl = keylink[kl]) if (seen[kl] == -1) { /* replacing old key kl, remove from schema and seen */ Id *osp; for (osp = schema; osp < sp; osp++) if (*osp == kl) { memmove(osp, osp + 1, (sp - osp) * sizeof(Id)); sp--; seen[kl] = 0; break; } } } } seen[*keyp] = keyp[1] + 1; } /* add solvables key if needed */ if (entry < 0 && data->end != data->start) { *sp++ = solvkeyid; /* always last in schema */ neednewschema = 1; } /* commit schema */ *sp = 0; if (neednewschema) /* Ideally we'd like to sort the new schema here, to ensure schema equality independend of the ordering. */ schemaid = repodata_schema2id(data, schema, 1); else schemaid = oldschemaid; if (entry < 0) { data->mainschemaoffsets = solv_calloc(sp - schema, sizeof(Id)); data->mainschema = schemaid; } /* find offsets in old incore data */ if (oldschemaid) { Id *lastneeded = 0; for (sp = data->schemadata + data->schemata[oldschemaid]; *sp; sp++) if (seen[*sp] == -1) lastneeded = sp + 1; if (lastneeded) { if (!oldincoreoffs) oldincoreoffs = solv_malloc2(data->nkeys, 2 * sizeof(Offset)); for (sp = data->schemadata + data->schemata[oldschemaid]; sp != lastneeded; sp++) { /* Skip the data associated with this old key. */ key = data->keys + *sp; ndp = dp; if (key->storage == KEY_STORAGE_VERTICAL_OFFSET) { ndp = data_skip(ndp, REPOKEY_TYPE_ID); ndp = data_skip(ndp, REPOKEY_TYPE_ID); } else if (key->storage == KEY_STORAGE_INCORE) ndp = data_skip_key(data, ndp, key); oldincoreoffs[*sp * 2] = dp - data->incoredata; oldincoreoffs[*sp * 2 + 1] = ndp - dp; dp = ndp; } } } /* just copy over the complete old entry (including the schemaid) if there was no new data */ if (entry >= 0 && !neednewschema && oldschemaid && (!data->attrs || !data->attrs[entry]) && dp) { ndp = data->incoredata + data->incoreoffset[entry]; data->incoreoffset[entry] = newincore.len; data_addblob(&newincore, ndp, dp - ndp); goto entrydone; } /* Now create data blob. We walk through the (possibly new) schema and either copy over old data, or insert the new. */ if (entry >= 0) data->incoreoffset[entry] = newincore.len; data_addid(&newincore, schemaid); /* we don't use a pointer to the schemadata here as repodata_serialize_key * may call repodata_schema2id() which might realloc our schemadata */ for (schemaidx = data->schemata[schemaid]; (keyid = data->schemadata[schemaidx]) != 0; schemaidx++) { if (entry < 0) { data->mainschemaoffsets[schemaidx - data->schemata[schemaid]] = newincore.len; if (keyid == solvkeyid) { /* add flexarray entry count */ data_addid(&newincore, data->end - data->start); break; /* always the last entry */ } } if (seen[keyid] == -1) { if (oldincoreoffs[keyid * 2 + 1]) data_addblob(&newincore, data->incoredata + oldincoreoffs[keyid * 2], oldincoreoffs[keyid * 2 + 1]); } else if (seen[keyid]) repodata_serialize_key(data, &newincore, &newvincore, schema, data->keys + keyid, seen[keyid] - 1); } entrydone: /* free memory */ if (entry >= 0 && data->attrs) { if (data->attrs[entry]) data->attrs[entry] = solv_free(data->attrs[entry]); if (entry && entry % 4096 == 0 && data->nxattrs <= 2 && entry + 64 < nentry) { compact_attrdata(data, entry + 1, nentry); /* try to free some memory */ #if 0 printf(" attr data: %d K\n", data->attrdatalen / 1024); printf(" attrid data: %d K\n", data->attriddatalen / (1024 / 4)); printf(" incore data: %d K\n", newincore.len / 1024); printf(" sum: %d K\n", (newincore.len + data->attrdatalen + data->attriddatalen * 4) / 1024); /* malloc_stats(); */ #endif } } } /* free all xattrs */ for (entry = 0; entry < data->nxattrs; entry++) if (data->xattrs[entry]) solv_free(data->xattrs[entry]); data->xattrs = solv_free(data->xattrs); data->nxattrs = 0; data->lasthandle = 0; data->lastkey = 0; data->lastdatalen = 0; solv_free(schema); solv_free(seen); solv_free(keylink); solv_free(oldincoreoffs); repodata_free_schemahash(data); solv_free(data->incoredata); data->incoredata = newincore.buf; data->incoredatalen = newincore.len; data->incoredatafree = 0; data->vincore = newvincore.buf; data->vincorelen = newvincore.len; data->attrs = solv_free(data->attrs); data->attrdata = solv_free(data->attrdata); data->attriddata = solv_free(data->attriddata); data->attrnum64data = solv_free(data->attrnum64data); data->attrdatalen = 0; data->attriddatalen = 0; data->attrnum64datalen = 0; #if 0 printf("repodata_internalize %d done\n", data->repodataid); printf(" incore data: %d K\n", data->incoredatalen / 1024); #endif } void repodata_disable_paging(Repodata *data) { if (maybe_load_repodata(data, 0)) { repopagestore_disable_paging(&data->store); data->storestate++; } } /* call the pool's loadcallback to load a stub repodata */ static void repodata_stub_loader(Repodata *data) { Repo *repo = data->repo; Pool *pool = repo->pool; int r, i; struct s_Pool_tmpspace oldtmpspace; Datapos oldpos; if (!pool->loadcallback) { data->state = REPODATA_ERROR; return; } data->state = REPODATA_LOADING; /* save tmp space and pos */ oldtmpspace = pool->tmpspace; memset(&pool->tmpspace, 0, sizeof(pool->tmpspace)); oldpos = pool->pos; r = pool->loadcallback(pool, data, pool->loadcallbackdata); /* restore tmp space and pos */ for (i = 0; i < POOL_TMPSPACEBUF; i++) solv_free(pool->tmpspace.buf[i]); pool->tmpspace = oldtmpspace; if (r && oldpos.repo == repo && oldpos.repodataid == data->repodataid) memset(&oldpos, 0, sizeof(oldpos)); pool->pos = oldpos; data->state = r ? REPODATA_AVAILABLE : REPODATA_ERROR; } static inline void repodata_add_stubkey(Repodata *data, Id keyname, Id keytype) { Repokey xkey; xkey.name = keyname; xkey.type = keytype; xkey.storage = KEY_STORAGE_INCORE; xkey.size = 0; repodata_key2id(data, &xkey, 1); } static Repodata * repodata_add_stub(Repodata **datap) { Repodata *data = *datap; Repo *repo = data->repo; Id repodataid = data - repo->repodata; Repodata *sdata = repo_add_repodata(repo, 0); data = repo->repodata + repodataid; if (data->end > data->start) repodata_extend_block(sdata, data->start, data->end - data->start); sdata->state = REPODATA_STUB; sdata->loadcallback = repodata_stub_loader; *datap = data; return sdata; } Repodata * repodata_create_stubs(Repodata *data) { Repo *repo = data->repo; Pool *pool = repo->pool; Repodata *sdata; int *stubdataids; Dataiterator di; Id xkeyname = 0; int i, cnt = 0; dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_EXTERNAL, 0, 0); while (dataiterator_step(&di)) if (di.data == data) cnt++; dataiterator_free(&di); if (!cnt) return data; stubdataids = solv_calloc(cnt, sizeof(*stubdataids)); for (i = 0; i < cnt; i++) { sdata = repodata_add_stub(&data); stubdataids[i] = sdata - repo->repodata; } i = 0; dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_EXTERNAL, 0, 0); sdata = 0; while (dataiterator_step(&di)) { if (di.data != data) continue; if (di.key->name == REPOSITORY_EXTERNAL && !di.nparents) { dataiterator_entersub(&di); sdata = repo->repodata + stubdataids[i++]; xkeyname = 0; continue; } repodata_set_kv(sdata, SOLVID_META, di.key->name, di.key->type, &di.kv); if (di.key->name == REPOSITORY_KEYS && di.key->type == REPOKEY_TYPE_IDARRAY) { if (!xkeyname) { if (!di.kv.eof) xkeyname = di.kv.id; } else { repodata_add_stubkey(sdata, xkeyname, di.kv.id); if (xkeyname == SOLVABLE_FILELIST) repodata_set_filelisttype(sdata, REPODATA_FILELIST_EXTENSION); xkeyname = 0; } } } dataiterator_free(&di); for (i = 0; i < cnt; i++) repodata_internalize(repo->repodata + stubdataids[i]); solv_free(stubdataids); return data; } void repodata_set_filelisttype(Repodata *data, int type) { data->filelisttype = type; } unsigned int repodata_memused(Repodata *data) { return data->incoredatalen + data->vincorelen; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_1357_0
crossvul-cpp_data_good_5239_0
/** * File: TGA Input * * Read TGA images. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "gd_tga.h" #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" /* Function: gdImageCreateFromTga Creates a gdImage from a TGA file Parameters: infile - Pointer to TGA binary file */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp) { gdImagePtr image; gdIOCtx* in = gdNewFileCtx(fp); if (in == NULL) return NULL; image = gdImageCreateFromTgaCtx(in); in->gd_free( in ); return image; } /* Function: gdImageCreateFromTgaPtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTgaCtx(in); in->gd_free(in); return im; } /* Function: gdImageCreateFromTgaCtx Creates a gdImage from a gdIOCtx referencing a TGA binary file. Parameters: ctx - Pointer to a gdIOCtx structure */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } /*! \brief Reads a TGA header. * Reads the header block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 1 on sucess, -1 on failure */ int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } /*! \brief Reads a TGA image data into buffer. * Reads the image data block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 0 on sucess, -1 on failure */ int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if (buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } /*! \brief Cleans up a TGA structure. * Dereferences the bitmap referenced in a TGA structure, then the structure itself * \param tga Pointer to TGA structure */ void free_tga(oTga * tga) { if (tga) { if (tga->ident) gdFree(tga->ident); if (tga->bitmap) gdFree(tga->bitmap); gdFree(tga); } }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5239_0
crossvul-cpp_data_good_261_0
/* * Copyright (c) 2000 William C. Fenner. * All rights reserved. * * Kevin Steves <ks@hp.se> July 2000 * Modified to: * - print version, type string and packet length * - print IP address count if > 1 (-v) * - verify checksum (-v) * - print authentication string (-v) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * The name of William C. Fenner may not be used to endorse or * promote products derived from this software without specific prior * written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. */ /* \summary: Virtual Router Redundancy Protocol (VRRP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ip.h" #include "ipproto.h" /* * RFC 2338 (VRRP v2): * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |Version| Type | Virtual Rtr ID| Priority | Count IP Addrs| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Auth Type | Adver Int | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IP Address (1) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IP Address (n) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Authentication Data (1) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Authentication Data (2) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * * RFC 5798 (VRRP v3): * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IPv4 Fields or IPv6 Fields | * ... ... * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |Version| Type | Virtual Rtr ID| Priority |Count IPvX Addr| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |(rsvd) | Max Adver Int | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | | * + + * | IPvX Address(es) | * + + * | | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ /* Type */ #define VRRP_TYPE_ADVERTISEMENT 1 static const struct tok type2str[] = { { VRRP_TYPE_ADVERTISEMENT, "Advertisement" }, { 0, NULL } }; /* Auth Type */ #define VRRP_AUTH_NONE 0 #define VRRP_AUTH_SIMPLE 1 #define VRRP_AUTH_AH 2 static const struct tok auth2str[] = { { VRRP_AUTH_NONE, "none" }, { VRRP_AUTH_SIMPLE, "simple" }, { VRRP_AUTH_AH, "ah" }, { 0, NULL } }; void vrrp_print(netdissect_options *ndo, register const u_char *bp, register u_int len, register const u_char *bp2, int ttl) { int version, type, auth_type = VRRP_AUTH_NONE; /* keep compiler happy */ const char *type_s; ND_TCHECK(bp[0]); version = (bp[0] & 0xf0) >> 4; type = bp[0] & 0x0f; type_s = tok2str(type2str, "unknown type (%u)", type); ND_PRINT((ndo, "VRRPv%u, %s", version, type_s)); if (ttl != 255) ND_PRINT((ndo, ", (ttl %u)", ttl)); if (version < 2 || version > 3 || type != VRRP_TYPE_ADVERTISEMENT) return; ND_TCHECK(bp[2]); ND_PRINT((ndo, ", vrid %u, prio %u", bp[1], bp[2])); ND_TCHECK(bp[5]); if (version == 2) { auth_type = bp[4]; ND_PRINT((ndo, ", authtype %s", tok2str(auth2str, NULL, auth_type))); ND_PRINT((ndo, ", intvl %us, length %u", bp[5], len)); } else { /* version == 3 */ uint16_t intvl = (bp[4] & 0x0f) << 8 | bp[5]; ND_PRINT((ndo, ", intvl %ucs, length %u", intvl, len)); } if (ndo->ndo_vflag) { int naddrs = bp[3]; int i; char c; if (version == 2 && ND_TTEST2(bp[0], len)) { struct cksum_vec vec[1]; vec[0].ptr = bp; vec[0].len = len; if (in_cksum(vec, 1)) { ND_TCHECK_16BITS(&bp[6]); ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } } if (version == 3 && ND_TTEST2(bp[0], len)) { uint16_t cksum = nextproto4_cksum(ndo, (const struct ip *)bp2, bp, len, len, IPPROTO_VRRP); if (cksum) ND_PRINT((ndo, ", (bad vrrp cksum %x)", EXTRACT_16BITS(&bp[6]))); } ND_PRINT((ndo, ", addrs")); if (naddrs > 1) ND_PRINT((ndo, "(%d)", naddrs)); ND_PRINT((ndo, ":")); c = ' '; bp += 8; for (i = 0; i < naddrs; i++) { ND_TCHECK(bp[3]); ND_PRINT((ndo, "%c%s", c, ipaddr_string(ndo, bp))); c = ','; bp += 4; } if (version == 2 && auth_type == VRRP_AUTH_SIMPLE) { /* simple text password */ ND_TCHECK(bp[7]); ND_PRINT((ndo, " auth \"")); if (fn_printn(ndo, bp, 8, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); } } return; trunc: ND_PRINT((ndo, "[|vrrp]")); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_261_0
crossvul-cpp_data_good_3068_1
/* * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #ifndef OPENSSL_NO_CHACHA # include <openssl/evp.h> # include <openssl/objects.h> # include "evp_locl.h" # include "internal/evp_int.h" # include "internal/chacha.h" typedef struct { union { double align; /* this ensures even sizeof(EVP_CHACHA_KEY)%8==0 */ unsigned int d[CHACHA_KEY_SIZE / 4]; } key; unsigned int counter[CHACHA_CTR_SIZE / 4]; unsigned char buf[CHACHA_BLK_SIZE]; unsigned int partial_len; } EVP_CHACHA_KEY; #define data(ctx) ((EVP_CHACHA_KEY *)(ctx)->cipher_data) static int chacha_init_key(EVP_CIPHER_CTX *ctx, const unsigned char user_key[CHACHA_KEY_SIZE], const unsigned char iv[CHACHA_CTR_SIZE], int enc) { EVP_CHACHA_KEY *key = data(ctx); unsigned int i; if (user_key) for (i = 0; i < CHACHA_KEY_SIZE; i+=4) { key->key.d[i/4] = CHACHA_U8TOU32(user_key+i); } if (iv) for (i = 0; i < CHACHA_CTR_SIZE; i+=4) { key->counter[i/4] = CHACHA_U8TOU32(iv+i); } key->partial_len = 0; return 1; } static int chacha_cipher(EVP_CIPHER_CTX * ctx, unsigned char *out, const unsigned char *inp, size_t len) { EVP_CHACHA_KEY *key = data(ctx); unsigned int n, rem, ctr32; if ((n = key->partial_len)) { while (len && n < CHACHA_BLK_SIZE) { *out++ = *inp++ ^ key->buf[n++]; len--; } key->partial_len = n; if (len == 0) return 1; if (n == CHACHA_BLK_SIZE) { key->partial_len = 0; key->counter[0]++; if (key->counter[0] == 0) key->counter[1]++; } } rem = (unsigned int)(len % CHACHA_BLK_SIZE); len -= rem; ctr32 = key->counter[0]; while (len >= CHACHA_BLK_SIZE) { size_t blocks = len / CHACHA_BLK_SIZE; /* * 1<<28 is just a not-so-small yet not-so-large number... * Below condition is practically never met, but it has to * be checked for code correctness. */ if (sizeof(size_t)>sizeof(unsigned int) && blocks>(1U<<28)) blocks = (1U<<28); /* * As ChaCha20_ctr32 operates on 32-bit counter, caller * has to handle overflow. 'if' below detects the * overflow, which is then handled by limiting the * amount of blocks to the exact overflow point... */ ctr32 += (unsigned int)blocks; if (ctr32 < blocks) { blocks -= ctr32; ctr32 = 0; } blocks *= CHACHA_BLK_SIZE; ChaCha20_ctr32(out, inp, blocks, key->key.d, key->counter); len -= blocks; inp += blocks; out += blocks; key->counter[0] = ctr32; if (ctr32 == 0) key->counter[1]++; } if (rem) { memset(key->buf, 0, sizeof(key->buf)); ChaCha20_ctr32(key->buf, key->buf, CHACHA_BLK_SIZE, key->key.d, key->counter); for (n = 0; n < rem; n++) out[n] = inp[n] ^ key->buf[n]; key->partial_len = rem; } return 1; } static const EVP_CIPHER chacha20 = { NID_chacha20, 1, /* block_size */ CHACHA_KEY_SIZE, /* key_len */ CHACHA_CTR_SIZE, /* iv_len, 128-bit counter in the context */ EVP_CIPH_CUSTOM_IV | EVP_CIPH_ALWAYS_CALL_INIT, chacha_init_key, chacha_cipher, NULL, sizeof(EVP_CHACHA_KEY), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_chacha20(void) { return (&chacha20); } # ifndef OPENSSL_NO_POLY1305 # include "internal/poly1305.h" typedef struct { EVP_CHACHA_KEY key; unsigned int nonce[12/4]; unsigned char tag[POLY1305_BLOCK_SIZE]; struct { uint64_t aad, text; } len; int aad, mac_inited, tag_len, nonce_len; size_t tls_payload_length; } EVP_CHACHA_AEAD_CTX; # define NO_TLS_PAYLOAD_LENGTH ((size_t)-1) # define aead_data(ctx) ((EVP_CHACHA_AEAD_CTX *)(ctx)->cipher_data) # define POLY1305_ctx(actx) ((POLY1305 *)(actx + 1)) static int chacha20_poly1305_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *inkey, const unsigned char *iv, int enc) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); if (!inkey && !iv) return 1; actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (iv != NULL) { unsigned char temp[CHACHA_CTR_SIZE] = { 0 }; /* pad on the left */ if (actx->nonce_len <= CHACHA_CTR_SIZE) memcpy(temp + CHACHA_CTR_SIZE - actx->nonce_len, iv, actx->nonce_len); chacha_init_key(ctx, inkey, temp, enc); actx->nonce[0] = actx->key.counter[1]; actx->nonce[1] = actx->key.counter[2]; actx->nonce[2] = actx->key.counter[3]; } else { chacha_init_key(ctx, inkey, NULL, enc); } return 1; } static int chacha20_poly1305_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); size_t rem, plen = actx->tls_payload_length; static const unsigned char zero[POLY1305_BLOCK_SIZE] = { 0 }; if (!actx->mac_inited) { actx->key.counter[0] = 0; memset(actx->key.buf, 0, sizeof(actx->key.buf)); ChaCha20_ctr32(actx->key.buf, actx->key.buf, CHACHA_BLK_SIZE, actx->key.key.d, actx->key.counter); Poly1305_Init(POLY1305_ctx(actx), actx->key.buf); actx->key.counter[0] = 1; actx->key.partial_len = 0; actx->len.aad = actx->len.text = 0; actx->mac_inited = 1; } if (in) { /* aad or text */ if (out == NULL) { /* aad */ Poly1305_Update(POLY1305_ctx(actx), in, len); actx->len.aad += len; actx->aad = 1; return len; } else { /* plain- or ciphertext */ if (actx->aad) { /* wrap up aad */ if ((rem = (size_t)actx->len.aad % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); actx->aad = 0; } actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; if (plen == NO_TLS_PAYLOAD_LENGTH) plen = len; else if (len != plen + POLY1305_BLOCK_SIZE) return -1; if (ctx->encrypt) { /* plaintext */ chacha_cipher(ctx, out, in, plen); Poly1305_Update(POLY1305_ctx(actx), out, plen); in += plen; out += plen; actx->len.text += plen; } else { /* ciphertext */ Poly1305_Update(POLY1305_ctx(actx), in, plen); chacha_cipher(ctx, out, in, plen); in += plen; out += plen; actx->len.text += plen; } } } if (in == NULL /* explicit final */ || plen != len) { /* or tls mode */ const union { long one; char little; } is_endian = { 1 }; unsigned char temp[POLY1305_BLOCK_SIZE]; if (actx->aad) { /* wrap up aad */ if ((rem = (size_t)actx->len.aad % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); actx->aad = 0; } if ((rem = (size_t)actx->len.text % POLY1305_BLOCK_SIZE)) Poly1305_Update(POLY1305_ctx(actx), zero, POLY1305_BLOCK_SIZE - rem); if (is_endian.little) { Poly1305_Update(POLY1305_ctx(actx), (unsigned char *)&actx->len, POLY1305_BLOCK_SIZE); } else { temp[0] = (unsigned char)(actx->len.aad); temp[1] = (unsigned char)(actx->len.aad>>8); temp[2] = (unsigned char)(actx->len.aad>>16); temp[3] = (unsigned char)(actx->len.aad>>24); temp[4] = (unsigned char)(actx->len.aad>>32); temp[5] = (unsigned char)(actx->len.aad>>40); temp[6] = (unsigned char)(actx->len.aad>>48); temp[7] = (unsigned char)(actx->len.aad>>56); temp[8] = (unsigned char)(actx->len.text); temp[9] = (unsigned char)(actx->len.text>>8); temp[10] = (unsigned char)(actx->len.text>>16); temp[11] = (unsigned char)(actx->len.text>>24); temp[12] = (unsigned char)(actx->len.text>>32); temp[13] = (unsigned char)(actx->len.text>>40); temp[14] = (unsigned char)(actx->len.text>>48); temp[15] = (unsigned char)(actx->len.text>>56); Poly1305_Update(POLY1305_ctx(actx), temp, POLY1305_BLOCK_SIZE); } Poly1305_Final(POLY1305_ctx(actx), ctx->encrypt ? actx->tag : temp); actx->mac_inited = 0; if (in != NULL && len != plen) { /* tls mode */ if (ctx->encrypt) { memcpy(out, actx->tag, POLY1305_BLOCK_SIZE); } else { if (CRYPTO_memcmp(temp, in, POLY1305_BLOCK_SIZE)) { memset(out - plen, 0, plen); return -1; } } } else if (!ctx->encrypt) { if (CRYPTO_memcmp(temp, actx->tag, actx->tag_len)) return -1; } } return len; } static int chacha20_poly1305_cleanup(EVP_CIPHER_CTX *ctx) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); if (actx) OPENSSL_cleanse(ctx->cipher_data, sizeof(*ctx) + Poly1305_ctx_size()); return 1; } static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); switch(type) { case EVP_CTRL_INIT: if (actx == NULL) actx = ctx->cipher_data = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size()); if (actx == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR); return 0; } actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tag_len = 0; actx->nonce_len = 12; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; return 1; case EVP_CTRL_COPY: if (actx) { EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr; dst->cipher_data = OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size()); if (dst->cipher_data == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR); return 0; } } return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0 || arg > CHACHA_CTR_SIZE) return 0; actx->nonce_len = arg; return 1; case EVP_CTRL_AEAD_SET_IV_FIXED: if (arg != 12) return 0; actx->nonce[0] = actx->key.counter[1] = CHACHA_U8TOU32((unsigned char *)ptr); actx->nonce[1] = actx->key.counter[2] = CHACHA_U8TOU32((unsigned char *)ptr+4); actx->nonce[2] = actx->key.counter[3] = CHACHA_U8TOU32((unsigned char *)ptr+8); return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE) return 0; if (ptr != NULL) { memcpy(actx->tag, ptr, arg); actx->tag_len = arg; } return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt) return 0; memcpy(ptr, actx->tag, arg); return 1; case EVP_CTRL_AEAD_TLS1_AAD: if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; { unsigned int len; unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE]; len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 | aad[EVP_AEAD_TLS1_AAD_LEN - 1]; if (!ctx->encrypt) { if (len < POLY1305_BLOCK_SIZE) return 0; len -= POLY1305_BLOCK_SIZE; /* discount attached tag */ memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2); aad = temp; temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8); temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len; } actx->tls_payload_length = len; /* * merge record sequence number as per RFC7905 */ actx->key.counter[1] = actx->nonce[0]; actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad); actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4); actx->mac_inited = 0; chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN); return POLY1305_BLOCK_SIZE; /* tag length */ } case EVP_CTRL_AEAD_SET_MAC_KEY: /* no-op */ return 1; default: return -1; } } static EVP_CIPHER chacha20_poly1305 = { NID_chacha20_poly1305, 1, /* block_size */ CHACHA_KEY_SIZE, /* key_len */ 12, /* iv_len, 96-bit nonce in the context */ EVP_CIPH_FLAG_AEAD_CIPHER | EVP_CIPH_CUSTOM_IV | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT | EVP_CIPH_CUSTOM_COPY | EVP_CIPH_FLAG_CUSTOM_CIPHER, chacha20_poly1305_init_key, chacha20_poly1305_cipher, chacha20_poly1305_cleanup, 0, /* 0 moves context-specific structure allocation to ctrl */ NULL, /* set_asn1_parameters */ NULL, /* get_asn1_parameters */ chacha20_poly1305_ctrl, NULL /* app_data */ }; const EVP_CIPHER *EVP_chacha20_poly1305(void) { return(&chacha20_poly1305); } # endif #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_3068_1
crossvul-cpp_data_good_2644_4
/* * Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Frame Relay printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "ethertype.h" #include "llc.h" #include "nlpid.h" #include "extract.h" #include "oui.h" static void frf15_print(netdissect_options *ndo, const u_char *, u_int); /* * the frame relay header has a variable length * * the EA bit determines if there is another byte * in the header * * minimum header length is 2 bytes * maximum header length is 4 bytes * * 7 6 5 4 3 2 1 0 * +----+----+----+----+----+----+----+----+ * | DLCI (6 bits) | CR | EA | * +----+----+----+----+----+----+----+----+ * | DLCI (4 bits) |FECN|BECN| DE | EA | * +----+----+----+----+----+----+----+----+ * | DLCI (7 bits) | EA | * +----+----+----+----+----+----+----+----+ * | DLCI (6 bits) |SDLC| EA | * +----+----+----+----+----+----+----+----+ */ #define FR_EA_BIT 0x01 #define FR_CR_BIT 0x02000000 #define FR_DE_BIT 0x00020000 #define FR_BECN_BIT 0x00040000 #define FR_FECN_BIT 0x00080000 #define FR_SDLC_BIT 0x00000002 static const struct tok fr_header_flag_values[] = { { FR_CR_BIT, "C!" }, { FR_DE_BIT, "DE" }, { FR_BECN_BIT, "BECN" }, { FR_FECN_BIT, "FECN" }, { FR_SDLC_BIT, "sdlcore" }, { 0, NULL } }; /* FRF.15 / FRF.16 */ #define MFR_B_BIT 0x80 #define MFR_E_BIT 0x40 #define MFR_C_BIT 0x20 #define MFR_BEC_MASK (MFR_B_BIT | MFR_E_BIT | MFR_C_BIT) #define MFR_CTRL_FRAME (MFR_B_BIT | MFR_E_BIT | MFR_C_BIT) #define MFR_FRAG_FRAME (MFR_B_BIT | MFR_E_BIT ) static const struct tok frf_flag_values[] = { { MFR_B_BIT, "Begin" }, { MFR_E_BIT, "End" }, { MFR_C_BIT, "Control" }, { 0, NULL } }; /* Finds out Q.922 address length, DLCI and flags. Returns 1 on success, * 0 on invalid address, -1 on truncated packet * save the flags dep. on address length */ static int parse_q922_addr(netdissect_options *ndo, const u_char *p, u_int *dlci, u_int *addr_len, uint8_t *flags, u_int length) { if (!ND_TTEST(p[0]) || length < 1) return -1; if ((p[0] & FR_EA_BIT)) return 0; if (!ND_TTEST(p[1]) || length < 2) return -1; *addr_len = 2; *dlci = ((p[0] & 0xFC) << 2) | ((p[1] & 0xF0) >> 4); flags[0] = p[0] & 0x02; /* populate the first flag fields */ flags[1] = p[1] & 0x0c; flags[2] = 0; /* clear the rest of the flags */ flags[3] = 0; if (p[1] & FR_EA_BIT) return 1; /* 2-byte Q.922 address */ p += 2; length -= 2; if (!ND_TTEST(p[0]) || length < 1) return -1; (*addr_len)++; /* 3- or 4-byte Q.922 address */ if ((p[0] & FR_EA_BIT) == 0) { *dlci = (*dlci << 7) | (p[0] >> 1); (*addr_len)++; /* 4-byte Q.922 address */ p++; length--; } if (!ND_TTEST(p[0]) || length < 1) return -1; if ((p[0] & FR_EA_BIT) == 0) return 0; /* more than 4 bytes of Q.922 address? */ flags[3] = p[0] & 0x02; *dlci = (*dlci << 6) | (p[0] >> 2); return 1; } char * q922_string(netdissect_options *ndo, const u_char *p, u_int length) { static u_int dlci, addr_len; static uint8_t flags[4]; static char buffer[sizeof("DLCI xxxxxxxxxx")]; memset(buffer, 0, sizeof(buffer)); if (parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length) == 1){ snprintf(buffer, sizeof(buffer), "DLCI %u", dlci); } return buffer; } /* Frame Relay packet structure, with flags and CRC removed +---------------------------+ | Q.922 Address* | +-- --+ | | +---------------------------+ | Control (UI = 0x03) | +---------------------------+ | Optional Pad (0x00) | +---------------------------+ | NLPID | +---------------------------+ | . | | . | | . | | Data | | . | | . | +---------------------------+ * Q.922 addresses, as presently defined, are two octets and contain a 10-bit DLCI. In some networks Q.922 addresses may optionally be increased to three or four octets. */ static void fr_hdr_print(netdissect_options *ndo, int length, u_int addr_len, u_int dlci, uint8_t *flags, uint16_t nlpid) { if (ndo->ndo_qflag) { ND_PRINT((ndo, "Q.922, DLCI %u, length %u: ", dlci, length)); } else { if (nlpid <= 0xff) /* if its smaller than 256 then its a NLPID */ ND_PRINT((ndo, "Q.922, hdr-len %u, DLCI %u, Flags [%s], NLPID %s (0x%02x), length %u: ", addr_len, dlci, bittok2str(fr_header_flag_values, "none", EXTRACT_32BITS(flags)), tok2str(nlpid_values,"unknown", nlpid), nlpid, length)); else /* must be an ethertype */ ND_PRINT((ndo, "Q.922, hdr-len %u, DLCI %u, Flags [%s], cisco-ethertype %s (0x%04x), length %u: ", addr_len, dlci, bittok2str(fr_header_flag_values, "none", EXTRACT_32BITS(flags)), tok2str(ethertype_values, "unknown", nlpid), nlpid, length)); } } u_int fr_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; ND_TCHECK2(*p, 4); /* minimum frame header length */ if ((length = fr_print(ndo, p, length)) == 0) return (0); else return length; trunc: ND_PRINT((ndo, "[|fr]")); return caplen; } u_int fr_print(netdissect_options *ndo, register const u_char *p, u_int length) { int ret; uint16_t extracted_ethertype; u_int dlci; u_int addr_len; uint16_t nlpid; u_int hdr_len; uint8_t flags[4]; ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length); if (ret == -1) goto trunc; if (ret == 0) { ND_PRINT((ndo, "Q.922, invalid address")); return 0; } ND_TCHECK(p[addr_len]); if (length < addr_len + 1) goto trunc; if (p[addr_len] != LLC_UI && dlci != 0) { /* * Let's figure out if we have Cisco-style encapsulation, * with an Ethernet type (Cisco HDLC type?) following the * address. */ if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) { /* no Ethertype */ ND_PRINT((ndo, "UI %02x! ", p[addr_len])); } else { extracted_ethertype = EXTRACT_16BITS(p+addr_len); if (ndo->ndo_eflag) fr_hdr_print(ndo, length, addr_len, dlci, flags, extracted_ethertype); if (ethertype_print(ndo, extracted_ethertype, p+addr_len+ETHERTYPE_LEN, length-addr_len-ETHERTYPE_LEN, ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "UI %02x! ", p[addr_len])); else return addr_len + 2; } } ND_TCHECK(p[addr_len+1]); if (length < addr_len + 2) goto trunc; if (p[addr_len + 1] == 0) { /* * Assume a pad byte after the control (UI) byte. * A pad byte should only be used with 3-byte Q.922. */ if (addr_len != 3) ND_PRINT((ndo, "Pad! ")); hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */; } else { /* * Not a pad byte. * A pad byte should be used with 3-byte Q.922. */ if (addr_len == 3) ND_PRINT((ndo, "No pad! ")); hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */; } ND_TCHECK(p[hdr_len - 1]); if (length < hdr_len) goto trunc; nlpid = p[hdr_len - 1]; if (ndo->ndo_eflag) fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid); p += hdr_len; length -= hdr_len; switch (nlpid) { case NLPID_IP: ip_print(ndo, p, length); break; case NLPID_IP6: ip6_print(ndo, p, length); break; case NLPID_CLNP: case NLPID_ESIS: case NLPID_ISIS: isoclns_print(ndo, p - 1, length + 1); /* OSI printers need the NLPID field */ break; case NLPID_SNAP: if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) { /* ether_type not known, print raw packet */ if (!ndo->ndo_eflag) fr_hdr_print(ndo, length + hdr_len, hdr_len, dlci, flags, nlpid); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p - hdr_len, length + hdr_len); } break; case NLPID_Q933: q933_print(ndo, p, length); break; case NLPID_MFR: frf15_print(ndo, p, length); break; case NLPID_PPP: ppp_print(ndo, p, length); break; default: if (!ndo->ndo_eflag) fr_hdr_print(ndo, length + hdr_len, addr_len, dlci, flags, nlpid); if (!ndo->ndo_xflag) ND_DEFAULTPRINT(p, length); } return hdr_len; trunc: ND_PRINT((ndo, "[|fr]")); return 0; } u_int mfr_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; ND_TCHECK2(*p, 2); /* minimum frame header length */ if ((length = mfr_print(ndo, p, length)) == 0) return (0); else return length; trunc: ND_PRINT((ndo, "[|mfr]")); return caplen; } #define MFR_CTRL_MSG_ADD_LINK 1 #define MFR_CTRL_MSG_ADD_LINK_ACK 2 #define MFR_CTRL_MSG_ADD_LINK_REJ 3 #define MFR_CTRL_MSG_HELLO 4 #define MFR_CTRL_MSG_HELLO_ACK 5 #define MFR_CTRL_MSG_REMOVE_LINK 6 #define MFR_CTRL_MSG_REMOVE_LINK_ACK 7 static const struct tok mfr_ctrl_msg_values[] = { { MFR_CTRL_MSG_ADD_LINK, "Add Link" }, { MFR_CTRL_MSG_ADD_LINK_ACK, "Add Link ACK" }, { MFR_CTRL_MSG_ADD_LINK_REJ, "Add Link Reject" }, { MFR_CTRL_MSG_HELLO, "Hello" }, { MFR_CTRL_MSG_HELLO_ACK, "Hello ACK" }, { MFR_CTRL_MSG_REMOVE_LINK, "Remove Link" }, { MFR_CTRL_MSG_REMOVE_LINK_ACK, "Remove Link ACK" }, { 0, NULL } }; #define MFR_CTRL_IE_BUNDLE_ID 1 #define MFR_CTRL_IE_LINK_ID 2 #define MFR_CTRL_IE_MAGIC_NUM 3 #define MFR_CTRL_IE_TIMESTAMP 5 #define MFR_CTRL_IE_VENDOR_EXT 6 #define MFR_CTRL_IE_CAUSE 7 static const struct tok mfr_ctrl_ie_values[] = { { MFR_CTRL_IE_BUNDLE_ID, "Bundle ID"}, { MFR_CTRL_IE_LINK_ID, "Link ID"}, { MFR_CTRL_IE_MAGIC_NUM, "Magic Number"}, { MFR_CTRL_IE_TIMESTAMP, "Timestamp"}, { MFR_CTRL_IE_VENDOR_EXT, "Vendor Extension"}, { MFR_CTRL_IE_CAUSE, "Cause"}, { 0, NULL } }; #define MFR_ID_STRING_MAXLEN 50 struct ie_tlv_header_t { uint8_t ie_type; uint8_t ie_len; }; u_int mfr_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int tlen,idx,hdr_len = 0; uint16_t sequence_num; uint8_t ie_type,ie_len; const uint8_t *tptr; /* * FRF.16 Link Integrity Control Frame * * 7 6 5 4 3 2 1 0 * +----+----+----+----+----+----+----+----+ * | B | E | C=1| 0 0 0 0 | EA | * +----+----+----+----+----+----+----+----+ * | 0 0 0 0 0 0 0 0 | * +----+----+----+----+----+----+----+----+ * | message type | * +----+----+----+----+----+----+----+----+ */ ND_TCHECK2(*p, 4); /* minimum frame header length */ if ((p[0] & MFR_BEC_MASK) == MFR_CTRL_FRAME && p[1] == 0) { ND_PRINT((ndo, "FRF.16 Control, Flags [%s], %s, length %u", bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK)), tok2str(mfr_ctrl_msg_values,"Unknown Message (0x%02x)",p[2]), length)); tptr = p + 3; tlen = length -3; hdr_len = 3; if (!ndo->ndo_vflag) return hdr_len; while (tlen>sizeof(struct ie_tlv_header_t)) { ND_TCHECK2(*tptr, sizeof(struct ie_tlv_header_t)); ie_type=tptr[0]; ie_len=tptr[1]; ND_PRINT((ndo, "\n\tIE %s (%u), length %u: ", tok2str(mfr_ctrl_ie_values,"Unknown",ie_type), ie_type, ie_len)); /* infinite loop check */ if (ie_type == 0 || ie_len <= sizeof(struct ie_tlv_header_t)) return hdr_len; ND_TCHECK2(*tptr, ie_len); tptr+=sizeof(struct ie_tlv_header_t); /* tlv len includes header */ ie_len-=sizeof(struct ie_tlv_header_t); tlen-=sizeof(struct ie_tlv_header_t); switch (ie_type) { case MFR_CTRL_IE_MAGIC_NUM: ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(tptr))); break; case MFR_CTRL_IE_BUNDLE_ID: /* same message format */ case MFR_CTRL_IE_LINK_ID: for (idx = 0; idx < ie_len && idx < MFR_ID_STRING_MAXLEN; idx++) { if (*(tptr+idx) != 0) /* don't print null termination */ safeputchar(ndo, *(tptr + idx)); else break; } break; case MFR_CTRL_IE_TIMESTAMP: if (ie_len == sizeof(struct timeval)) { ts_print(ndo, (const struct timeval *)tptr); break; } /* fall through and hexdump if no unix timestamp */ ND_FALL_THROUGH; /* * FIXME those are the defined IEs that lack a decoder * you are welcome to contribute code ;-) */ case MFR_CTRL_IE_VENDOR_EXT: case MFR_CTRL_IE_CAUSE: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", ie_len); break; } /* do we want to see a hexdump of the IE ? */ if (ndo->ndo_vflag > 1 ) print_unknown_data(ndo, tptr, "\n\t ", ie_len); tlen-=ie_len; tptr+=ie_len; } return hdr_len; } /* * FRF.16 Fragmentation Frame * * 7 6 5 4 3 2 1 0 * +----+----+----+----+----+----+----+----+ * | B | E | C=0|seq. (high 4 bits) | EA | * +----+----+----+----+----+----+----+----+ * | sequence (low 8 bits) | * +----+----+----+----+----+----+----+----+ * | DLCI (6 bits) | CR | EA | * +----+----+----+----+----+----+----+----+ * | DLCI (4 bits) |FECN|BECN| DE | EA | * +----+----+----+----+----+----+----+----+ */ sequence_num = (p[0]&0x1e)<<7 | p[1]; /* whole packet or first fragment ? */ if ((p[0] & MFR_BEC_MASK) == MFR_FRAG_FRAME || (p[0] & MFR_BEC_MASK) == MFR_B_BIT) { ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s], ", sequence_num, bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK)))); hdr_len = 2; fr_print(ndo, p+hdr_len,length-hdr_len); return hdr_len; } /* must be a middle or the last fragment */ ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s]", sequence_num, bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK)))); print_unknown_data(ndo, p, "\n\t", length); return hdr_len; trunc: ND_PRINT((ndo, "[|mfr]")); return length; } /* an NLPID of 0xb1 indicates a 2-byte * FRF.15 header * * 7 6 5 4 3 2 1 0 * +----+----+----+----+----+----+----+----+ * ~ Q.922 header ~ * +----+----+----+----+----+----+----+----+ * | NLPID (8 bits) | NLPID=0xb1 * +----+----+----+----+----+----+----+----+ * | B | E | C |seq. (high 4 bits) | R | * +----+----+----+----+----+----+----+----+ * | sequence (low 8 bits) | * +----+----+----+----+----+----+----+----+ */ #define FR_FRF15_FRAGTYPE 0x01 static void frf15_print(netdissect_options *ndo, const u_char *p, u_int length) { uint16_t sequence_num, flags; if (length < 2) goto trunc; ND_TCHECK2(*p, 2); flags = p[0]&MFR_BEC_MASK; sequence_num = (p[0]&0x1e)<<7 | p[1]; ND_PRINT((ndo, "FRF.15, seq 0x%03x, Flags [%s],%s Fragmentation, length %u", sequence_num, bittok2str(frf_flag_values,"none",flags), p[0]&FR_FRF15_FRAGTYPE ? "Interface" : "End-to-End", length)); /* TODO: * depending on all permutations of the B, E and C bit * dig as deep as we can - e.g. on the first (B) fragment * there is enough payload to print the IP header * on non (B) fragments it depends if the fragmentation * model is end-to-end or interface based wether we want to print * another Q.922 header */ return; trunc: ND_PRINT((ndo, "[|frf.15]")); } /* * Q.933 decoding portion for framerelay specific. */ /* Q.933 packet format Format of Other Protocols using Q.933 NLPID +-------------------------------+ | Q.922 Address | +---------------+---------------+ |Control 0x03 | NLPID 0x08 | +---------------+---------------+ | L2 Protocol ID | | octet 1 | octet 2 | +-------------------------------+ | L3 Protocol ID | | octet 2 | octet 2 | +-------------------------------+ | Protocol Data | +-------------------------------+ | FCS | +-------------------------------+ */ /* L2 (Octet 1)- Call Reference Usually is 0x0 */ /* * L2 (Octet 2)- Message Types definition 1 byte long. */ /* Call Establish */ #define MSG_TYPE_ESC_TO_NATIONAL 0x00 #define MSG_TYPE_ALERT 0x01 #define MSG_TYPE_CALL_PROCEEDING 0x02 #define MSG_TYPE_CONNECT 0x07 #define MSG_TYPE_CONNECT_ACK 0x0F #define MSG_TYPE_PROGRESS 0x03 #define MSG_TYPE_SETUP 0x05 /* Call Clear */ #define MSG_TYPE_DISCONNECT 0x45 #define MSG_TYPE_RELEASE 0x4D #define MSG_TYPE_RELEASE_COMPLETE 0x5A #define MSG_TYPE_RESTART 0x46 #define MSG_TYPE_RESTART_ACK 0x4E /* Status */ #define MSG_TYPE_STATUS 0x7D #define MSG_TYPE_STATUS_ENQ 0x75 static const struct tok fr_q933_msg_values[] = { { MSG_TYPE_ESC_TO_NATIONAL, "ESC to National" }, { MSG_TYPE_ALERT, "Alert" }, { MSG_TYPE_CALL_PROCEEDING, "Call proceeding" }, { MSG_TYPE_CONNECT, "Connect" }, { MSG_TYPE_CONNECT_ACK, "Connect ACK" }, { MSG_TYPE_PROGRESS, "Progress" }, { MSG_TYPE_SETUP, "Setup" }, { MSG_TYPE_DISCONNECT, "Disconnect" }, { MSG_TYPE_RELEASE, "Release" }, { MSG_TYPE_RELEASE_COMPLETE, "Release Complete" }, { MSG_TYPE_RESTART, "Restart" }, { MSG_TYPE_RESTART_ACK, "Restart ACK" }, { MSG_TYPE_STATUS, "Status Reply" }, { MSG_TYPE_STATUS_ENQ, "Status Enquiry" }, { 0, NULL } }; #define IE_IS_SINGLE_OCTET(iecode) ((iecode) & 0x80) #define IE_IS_SHIFT(iecode) (((iecode) & 0xF0) == 0x90) #define IE_SHIFT_IS_NON_LOCKING(iecode) ((iecode) & 0x08) #define IE_SHIFT_IS_LOCKING(iecode) (!(IE_SHIFT_IS_NON_LOCKING(iecode))) #define IE_SHIFT_CODESET(iecode) ((iecode) & 0x07) #define FR_LMI_ANSI_REPORT_TYPE_IE 0x01 #define FR_LMI_ANSI_LINK_VERIFY_IE_91 0x19 /* details? */ #define FR_LMI_ANSI_LINK_VERIFY_IE 0x03 #define FR_LMI_ANSI_PVC_STATUS_IE 0x07 #define FR_LMI_CCITT_REPORT_TYPE_IE 0x51 #define FR_LMI_CCITT_LINK_VERIFY_IE 0x53 #define FR_LMI_CCITT_PVC_STATUS_IE 0x57 static const struct tok fr_q933_ie_values_codeset_0_5[] = { { FR_LMI_ANSI_REPORT_TYPE_IE, "ANSI Report Type" }, { FR_LMI_ANSI_LINK_VERIFY_IE_91, "ANSI Link Verify" }, { FR_LMI_ANSI_LINK_VERIFY_IE, "ANSI Link Verify" }, { FR_LMI_ANSI_PVC_STATUS_IE, "ANSI PVC Status" }, { FR_LMI_CCITT_REPORT_TYPE_IE, "CCITT Report Type" }, { FR_LMI_CCITT_LINK_VERIFY_IE, "CCITT Link Verify" }, { FR_LMI_CCITT_PVC_STATUS_IE, "CCITT PVC Status" }, { 0, NULL } }; #define FR_LMI_REPORT_TYPE_IE_FULL_STATUS 0 #define FR_LMI_REPORT_TYPE_IE_LINK_VERIFY 1 #define FR_LMI_REPORT_TYPE_IE_ASYNC_PVC 2 static const struct tok fr_lmi_report_type_ie_values[] = { { FR_LMI_REPORT_TYPE_IE_FULL_STATUS, "Full Status" }, { FR_LMI_REPORT_TYPE_IE_LINK_VERIFY, "Link verify" }, { FR_LMI_REPORT_TYPE_IE_ASYNC_PVC, "Async PVC Status" }, { 0, NULL } }; /* array of 16 codesets - currently we only support codepage 0 and 5 */ static const struct tok *fr_q933_ie_codesets[] = { fr_q933_ie_values_codeset_0_5, NULL, NULL, NULL, NULL, fr_q933_ie_values_codeset_0_5, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; static int fr_q933_print_ie_codeset_0_5(netdissect_options *ndo, u_int iecode, u_int ielength, const u_char *p); typedef int (*codeset_pr_func_t)(netdissect_options *, u_int iecode, u_int ielength, const u_char *p); /* array of 16 codesets - currently we only support codepage 0 and 5 */ static const codeset_pr_func_t fr_q933_print_ie_codeset[] = { fr_q933_print_ie_codeset_0_5, NULL, NULL, NULL, NULL, fr_q933_print_ie_codeset_0_5, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; /* * ITU-T Q.933. * * p points to octet 2, the octet containing the length of the * call reference value, so p[n] is octet n+2 ("octet X" is as * used in Q.931/Q.933). * * XXX - actually used both for Q.931 and Q.933. */ void q933_print(netdissect_options *ndo, const u_char *p, u_int length) { u_int olen; u_int call_ref_length, i; uint8_t call_ref[15]; /* maximum length - length field is 4 bits */ u_int msgtype; u_int iecode; u_int ielength; u_int codeset = 0; u_int is_ansi = 0; u_int ie_is_known; u_int non_locking_shift; u_int unshift_codeset; ND_PRINT((ndo, "%s", ndo->ndo_eflag ? "" : "Q.933")); if (length == 0 || !ND_TTEST(*p)) { if (!ndo->ndo_eflag) ND_PRINT((ndo, ", ")); ND_PRINT((ndo, "length %u", length)); goto trunc; } /* * Get the length of the call reference value. */ olen = length; /* preserve the original length for display */ call_ref_length = (*p) & 0x0f; p++; length--; /* * Get the call reference value. */ for (i = 0; i < call_ref_length; i++) { if (length == 0 || !ND_TTEST(*p)) { if (!ndo->ndo_eflag) ND_PRINT((ndo, ", ")); ND_PRINT((ndo, "length %u", olen)); goto trunc; } call_ref[i] = *p; p++; length--; } /* * Get the message type. */ if (length == 0 || !ND_TTEST(*p)) { if (!ndo->ndo_eflag) ND_PRINT((ndo, ", ")); ND_PRINT((ndo, "length %u", olen)); goto trunc; } msgtype = *p; p++; length--; /* * Peek ahead to see if we start with a shift. */ non_locking_shift = 0; unshift_codeset = codeset; if (length != 0) { if (!ND_TTEST(*p)) { if (!ndo->ndo_eflag) ND_PRINT((ndo, ", ")); ND_PRINT((ndo, "length %u", olen)); goto trunc; } iecode = *p; if (IE_IS_SHIFT(iecode)) { /* * It's a shift. Skip over it. */ p++; length--; /* * Get the codeset. */ codeset = IE_SHIFT_CODESET(iecode); /* * If it's a locking shift to codeset 5, * mark this as ANSI. (XXX - 5 is actually * for national variants in general, not * the US variant in particular, but maybe * this is more American exceptionalism. :-)) */ if (IE_SHIFT_IS_LOCKING(iecode)) { /* * It's a locking shift. */ if (codeset == 5) { /* * It's a locking shift to * codeset 5, so this is * T1.617 Annex D. */ is_ansi = 1; } } else { /* * It's a non-locking shift. * Remember the current codeset, so we * can revert to it after the next IE. */ non_locking_shift = 1; unshift_codeset = 0; } } } /* printing out header part */ if (!ndo->ndo_eflag) ND_PRINT((ndo, ", ")); ND_PRINT((ndo, "%s, codeset %u", is_ansi ? "ANSI" : "CCITT", codeset)); if (call_ref_length != 0) { ND_TCHECK(p[0]); if (call_ref_length > 1 || p[0] != 0) { /* * Not a dummy call reference. */ ND_PRINT((ndo, ", Call Ref: 0x")); for (i = 0; i < call_ref_length; i++) ND_PRINT((ndo, "%02x", call_ref[i])); } } if (ndo->ndo_vflag) { ND_PRINT((ndo, ", %s (0x%02x), length %u", tok2str(fr_q933_msg_values, "unknown message", msgtype), msgtype, olen)); } else { ND_PRINT((ndo, ", %s", tok2str(fr_q933_msg_values, "unknown message 0x%02x", msgtype))); } /* Loop through the rest of the IEs */ while (length != 0) { /* * What's the state of any non-locking shifts? */ if (non_locking_shift == 1) { /* * There's a non-locking shift in effect for * this IE. Count it, so we reset the codeset * before the next IE. */ non_locking_shift = 2; } else if (non_locking_shift == 2) { /* * Unshift. */ codeset = unshift_codeset; non_locking_shift = 0; } /* * Get the first octet of the IE. */ if (!ND_TTEST(*p)) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", length %u", olen)); } goto trunc; } iecode = *p; p++; length--; /* Single-octet IE? */ if (IE_IS_SINGLE_OCTET(iecode)) { /* * Yes. Is it a shift? */ if (IE_IS_SHIFT(iecode)) { /* * Yes. Is it locking? */ if (IE_SHIFT_IS_LOCKING(iecode)) { /* * Yes. */ non_locking_shift = 0; } else { /* * No. Remember the current * codeset, so we can revert * to it after the next IE. */ non_locking_shift = 1; unshift_codeset = codeset; } /* * Get the codeset. */ codeset = IE_SHIFT_CODESET(iecode); } } else { /* * No. Get the IE length. */ if (length == 0 || !ND_TTEST(*p)) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", length %u", olen)); } goto trunc; } ielength = *p; p++; length--; /* lets do the full IE parsing only in verbose mode * however some IEs (DLCI Status, Link Verify) * are also interesting in non-verbose mode */ if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t%s IE (0x%02x), length %u: ", tok2str(fr_q933_ie_codesets[codeset], "unknown", iecode), iecode, ielength)); } /* sanity checks */ if (iecode == 0 || ielength == 0) { return; } if (length < ielength || !ND_TTEST2(*p, ielength)) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", length %u", olen)); } goto trunc; } ie_is_known = 0; if (fr_q933_print_ie_codeset[codeset] != NULL) { ie_is_known = fr_q933_print_ie_codeset[codeset](ndo, iecode, ielength, p); } if (ie_is_known) { /* * Known IE; do we want to see a hexdump * of it? */ if (ndo->ndo_vflag > 1) { /* Yes. */ print_unknown_data(ndo, p, "\n\t ", ielength); } } else { /* * Unknown IE; if we're printing verbosely, * print its content in hex. */ if (ndo->ndo_vflag >= 1) { print_unknown_data(ndo, p, "\n\t", ielength); } } length -= ielength; p += ielength; } } if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", length %u", olen)); } return; trunc: ND_PRINT((ndo, "[|q.933]")); } static int fr_q933_print_ie_codeset_0_5(netdissect_options *ndo, u_int iecode, u_int ielength, const u_char *p) { u_int dlci; switch (iecode) { case FR_LMI_ANSI_REPORT_TYPE_IE: /* fall through */ case FR_LMI_CCITT_REPORT_TYPE_IE: if (ielength < 1) { if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", ")); } ND_PRINT((ndo, "Invalid REPORT TYPE IE")); return 1; } if (ndo->ndo_vflag) { ND_PRINT((ndo, "%s (%u)", tok2str(fr_lmi_report_type_ie_values,"unknown",p[0]), p[0])); } return 1; case FR_LMI_ANSI_LINK_VERIFY_IE: /* fall through */ case FR_LMI_CCITT_LINK_VERIFY_IE: case FR_LMI_ANSI_LINK_VERIFY_IE_91: if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", ")); } if (ielength < 2) { ND_PRINT((ndo, "Invalid LINK VERIFY IE")); return 1; } ND_PRINT((ndo, "TX Seq: %3d, RX Seq: %3d", p[0], p[1])); return 1; case FR_LMI_ANSI_PVC_STATUS_IE: /* fall through */ case FR_LMI_CCITT_PVC_STATUS_IE: if (!ndo->ndo_vflag) { ND_PRINT((ndo, ", ")); } /* now parse the DLCI information element. */ if ((ielength < 3) || (p[0] & 0x80) || ((ielength == 3) && !(p[1] & 0x80)) || ((ielength == 4) && ((p[1] & 0x80) || !(p[2] & 0x80))) || ((ielength == 5) && ((p[1] & 0x80) || (p[2] & 0x80) || !(p[3] & 0x80))) || (ielength > 5) || !(p[ielength - 1] & 0x80)) { ND_PRINT((ndo, "Invalid DLCI in PVC STATUS IE")); return 1; } dlci = ((p[0] & 0x3F) << 4) | ((p[1] & 0x78) >> 3); if (ielength == 4) { dlci = (dlci << 6) | ((p[2] & 0x7E) >> 1); } else if (ielength == 5) { dlci = (dlci << 13) | (p[2] & 0x7F) | ((p[3] & 0x7E) >> 1); } ND_PRINT((ndo, "DLCI %u: status %s%s", dlci, p[ielength - 1] & 0x8 ? "New, " : "", p[ielength - 1] & 0x2 ? "Active" : "Inactive")); return 1; } return 0; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_4
crossvul-cpp_data_good_1328_0
/* * Copyright (c) Red Hat Inc. * 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, sub license, * 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 (including the * next paragraph) 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 NON-INFRINGEMENT. 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. * * Authors: Dave Airlie <airlied@redhat.com> * Jerome Glisse <jglisse@redhat.com> * Pauli Nieminen <suokkos@gmail.com> */ /* simple list based uncached page pool * - Pool collects resently freed pages for reuse * - Use page->lru to keep a free list * - doesn't track currently in use pages */ #define pr_fmt(fmt) "[TTM] " fmt #include <linux/list.h> #include <linux/spinlock.h> #include <linux/highmem.h> #include <linux/mm_types.h> #include <linux/module.h> #include <linux/mm.h> #include <linux/seq_file.h> /* for seq_printf */ #include <linux/slab.h> #include <linux/dma-mapping.h> #include <linux/atomic.h> #include <drm/ttm/ttm_bo_driver.h> #include <drm/ttm/ttm_page_alloc.h> #include <drm/ttm/ttm_set_memory.h> #define NUM_PAGES_TO_ALLOC (PAGE_SIZE/sizeof(struct page *)) #define SMALL_ALLOCATION 16 #define FREE_ALL_PAGES (~0U) /* times are in msecs */ #define PAGE_FREE_INTERVAL 1000 /** * struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages. * * @lock: Protects the shared pool from concurrnet access. Must be used with * irqsave/irqrestore variants because pool allocator maybe called from * delayed work. * @fill_lock: Prevent concurrent calls to fill. * @list: Pool of free uc/wc pages for fast reuse. * @gfp_flags: Flags to pass for alloc_page. * @npages: Number of pages in pool. */ struct ttm_page_pool { spinlock_t lock; bool fill_lock; struct list_head list; gfp_t gfp_flags; unsigned npages; char *name; unsigned long nfrees; unsigned long nrefills; unsigned int order; }; /** * Limits for the pool. They are handled without locks because only place where * they may change is in sysfs store. They won't have immediate effect anyway * so forcing serialization to access them is pointless. */ struct ttm_pool_opts { unsigned alloc_size; unsigned max_size; unsigned small; }; #define NUM_POOLS 6 /** * struct ttm_pool_manager - Holds memory pools for fst allocation * * Manager is read only object for pool code so it doesn't need locking. * * @free_interval: minimum number of jiffies between freeing pages from pool. * @page_alloc_inited: reference counting for pool allocation. * @work: Work that is used to shrink the pool. Work is only run when there is * some pages to free. * @small_allocation: Limit in number of pages what is small allocation. * * @pools: All pool objects in use. **/ struct ttm_pool_manager { struct kobject kobj; struct shrinker mm_shrink; struct ttm_pool_opts options; union { struct ttm_page_pool pools[NUM_POOLS]; struct { struct ttm_page_pool wc_pool; struct ttm_page_pool uc_pool; struct ttm_page_pool wc_pool_dma32; struct ttm_page_pool uc_pool_dma32; struct ttm_page_pool wc_pool_huge; struct ttm_page_pool uc_pool_huge; } ; }; }; static struct attribute ttm_page_pool_max = { .name = "pool_max_size", .mode = S_IRUGO | S_IWUSR }; static struct attribute ttm_page_pool_small = { .name = "pool_small_allocation", .mode = S_IRUGO | S_IWUSR }; static struct attribute ttm_page_pool_alloc_size = { .name = "pool_allocation_size", .mode = S_IRUGO | S_IWUSR }; static struct attribute *ttm_pool_attrs[] = { &ttm_page_pool_max, &ttm_page_pool_small, &ttm_page_pool_alloc_size, NULL }; static void ttm_pool_kobj_release(struct kobject *kobj) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); kfree(m); } static ssize_t ttm_pool_store(struct kobject *kobj, struct attribute *attr, const char *buffer, size_t size) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); int chars; unsigned val; chars = sscanf(buffer, "%u", &val); if (chars == 0) return size; /* Convert kb to number of pages */ val = val / (PAGE_SIZE >> 10); if (attr == &ttm_page_pool_max) m->options.max_size = val; else if (attr == &ttm_page_pool_small) m->options.small = val; else if (attr == &ttm_page_pool_alloc_size) { if (val > NUM_PAGES_TO_ALLOC*8) { pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n", NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7), NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10)); return size; } else if (val > NUM_PAGES_TO_ALLOC) { pr_warn("Setting allocation size to larger than %lu is not recommended\n", NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10)); } m->options.alloc_size = val; } return size; } static ssize_t ttm_pool_show(struct kobject *kobj, struct attribute *attr, char *buffer) { struct ttm_pool_manager *m = container_of(kobj, struct ttm_pool_manager, kobj); unsigned val = 0; if (attr == &ttm_page_pool_max) val = m->options.max_size; else if (attr == &ttm_page_pool_small) val = m->options.small; else if (attr == &ttm_page_pool_alloc_size) val = m->options.alloc_size; val = val * (PAGE_SIZE >> 10); return snprintf(buffer, PAGE_SIZE, "%u\n", val); } static const struct sysfs_ops ttm_pool_sysfs_ops = { .show = &ttm_pool_show, .store = &ttm_pool_store, }; static struct kobj_type ttm_pool_kobj_type = { .release = &ttm_pool_kobj_release, .sysfs_ops = &ttm_pool_sysfs_ops, .default_attrs = ttm_pool_attrs, }; static struct ttm_pool_manager *_manager; /** * Select the right pool or requested caching state and ttm flags. */ static struct ttm_page_pool *ttm_get_pool(int flags, bool huge, enum ttm_caching_state cstate) { int pool_index; if (cstate == tt_cached) return NULL; if (cstate == tt_wc) pool_index = 0x0; else pool_index = 0x1; if (flags & TTM_PAGE_FLAG_DMA32) { if (huge) return NULL; pool_index |= 0x2; } else if (huge) { pool_index |= 0x4; } return &_manager->pools[pool_index]; } /* set memory back to wb and free the pages. */ static void ttm_pages_put(struct page *pages[], unsigned npages, unsigned int order) { unsigned int i, pages_nr = (1 << order); if (order == 0) { if (ttm_set_pages_array_wb(pages, npages)) pr_err("Failed to set %d pages to wb!\n", npages); } for (i = 0; i < npages; ++i) { if (order > 0) { if (ttm_set_pages_wb(pages[i], pages_nr)) pr_err("Failed to set %d pages to wb!\n", pages_nr); } __free_pages(pages[i], order); } } static void ttm_pool_update_free_locked(struct ttm_page_pool *pool, unsigned freed_pages) { pool->npages -= freed_pages; pool->nfrees += freed_pages; } /** * Free pages from pool. * * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC * number of pages in one go. * * @pool: to free the pages from * @free_all: If set to true will free all pages in pool * @use_static: Safe to use static buffer **/ static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free, bool use_static) { static struct page *static_buf[NUM_PAGES_TO_ALLOC]; unsigned long irq_flags; struct page *p; struct page **pages_to_free; unsigned freed_pages = 0, npages_to_free = nr_free; if (NUM_PAGES_TO_ALLOC < nr_free) npages_to_free = NUM_PAGES_TO_ALLOC; if (use_static) pages_to_free = static_buf; else pages_to_free = kmalloc_array(npages_to_free, sizeof(struct page *), GFP_KERNEL); if (!pages_to_free) { pr_debug("Failed to allocate memory for pool free operation\n"); return 0; } restart: spin_lock_irqsave(&pool->lock, irq_flags); list_for_each_entry_reverse(p, &pool->list, lru) { if (freed_pages >= npages_to_free) break; pages_to_free[freed_pages++] = p; /* We can only remove NUM_PAGES_TO_ALLOC at a time. */ if (freed_pages >= NUM_PAGES_TO_ALLOC) { /* remove range of pages from the pool */ __list_del(p->lru.prev, &pool->list); ttm_pool_update_free_locked(pool, freed_pages); /** * Because changing page caching is costly * we unlock the pool to prevent stalling. */ spin_unlock_irqrestore(&pool->lock, irq_flags); ttm_pages_put(pages_to_free, freed_pages, pool->order); if (likely(nr_free != FREE_ALL_PAGES)) nr_free -= freed_pages; if (NUM_PAGES_TO_ALLOC >= nr_free) npages_to_free = nr_free; else npages_to_free = NUM_PAGES_TO_ALLOC; freed_pages = 0; /* free all so restart the processing */ if (nr_free) goto restart; /* Not allowed to fall through or break because * following context is inside spinlock while we are * outside here. */ goto out; } } /* remove range of pages from the pool */ if (freed_pages) { __list_del(&p->lru, &pool->list); ttm_pool_update_free_locked(pool, freed_pages); nr_free -= freed_pages; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (freed_pages) ttm_pages_put(pages_to_free, freed_pages, pool->order); out: if (pages_to_free != static_buf) kfree(pages_to_free); return nr_free; } /** * Callback for mm to request pool to reduce number of page held. * * XXX: (dchinner) Deadlock warning! * * This code is crying out for a shrinker per pool.... */ static unsigned long ttm_pool_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) { static DEFINE_MUTEX(lock); static unsigned start_pool; unsigned i; unsigned pool_offset; struct ttm_page_pool *pool; int shrink_pages = sc->nr_to_scan; unsigned long freed = 0; unsigned int nr_free_pool; if (!mutex_trylock(&lock)) return SHRINK_STOP; pool_offset = ++start_pool % NUM_POOLS; /* select start pool in round robin fashion */ for (i = 0; i < NUM_POOLS; ++i) { unsigned nr_free = shrink_pages; unsigned page_nr; if (shrink_pages == 0) break; pool = &_manager->pools[(i + pool_offset)%NUM_POOLS]; page_nr = (1 << pool->order); /* OK to use static buffer since global mutex is held. */ nr_free_pool = roundup(nr_free, page_nr) >> pool->order; shrink_pages = ttm_page_pool_free(pool, nr_free_pool, true); freed += (nr_free_pool - shrink_pages) << pool->order; if (freed >= sc->nr_to_scan) break; shrink_pages <<= pool->order; } mutex_unlock(&lock); return freed; } static unsigned long ttm_pool_shrink_count(struct shrinker *shrink, struct shrink_control *sc) { unsigned i; unsigned long count = 0; struct ttm_page_pool *pool; for (i = 0; i < NUM_POOLS; ++i) { pool = &_manager->pools[i]; count += (pool->npages << pool->order); } return count; } static int ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager) { manager->mm_shrink.count_objects = ttm_pool_shrink_count; manager->mm_shrink.scan_objects = ttm_pool_shrink_scan; manager->mm_shrink.seeks = 1; return register_shrinker(&manager->mm_shrink); } static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager) { unregister_shrinker(&manager->mm_shrink); } static int ttm_set_pages_caching(struct page **pages, enum ttm_caching_state cstate, unsigned cpages) { int r = 0; /* Set page caching */ switch (cstate) { case tt_uncached: r = ttm_set_pages_array_uc(pages, cpages); if (r) pr_err("Failed to set %d pages to uc!\n", cpages); break; case tt_wc: r = ttm_set_pages_array_wc(pages, cpages); if (r) pr_err("Failed to set %d pages to wc!\n", cpages); break; default: break; } return r; } /** * Free pages the pages that failed to change the caching state. If there is * any pages that have changed their caching state already put them to the * pool. */ static void ttm_handle_caching_state_failure(struct list_head *pages, int ttm_flags, enum ttm_caching_state cstate, struct page **failed_pages, unsigned cpages) { unsigned i; /* Failed pages have to be freed */ for (i = 0; i < cpages; ++i) { list_del(&failed_pages[i]->lru); __free_page(failed_pages[i]); } } /** * Allocate new pages with correct caching. * * This function is reentrant if caller updates count depending on number of * pages returned in pages array. */ static int ttm_alloc_new_pages(struct list_head *pages, gfp_t gfp_flags, int ttm_flags, enum ttm_caching_state cstate, unsigned count, unsigned order) { struct page **caching_array; struct page *p; int r = 0; unsigned i, j, cpages; unsigned npages = 1 << order; unsigned max_cpages = min(count << order, (unsigned)NUM_PAGES_TO_ALLOC); /* allocate array for page caching change */ caching_array = kmalloc_array(max_cpages, sizeof(struct page *), GFP_KERNEL); if (!caching_array) { pr_debug("Unable to allocate table for new pages\n"); return -ENOMEM; } for (i = 0, cpages = 0; i < count; ++i) { p = alloc_pages(gfp_flags, order); if (!p) { pr_debug("Unable to get page %u\n", i); /* store already allocated pages in the pool after * setting the caching state */ if (cpages) { r = ttm_set_pages_caching(caching_array, cstate, cpages); if (r) ttm_handle_caching_state_failure(pages, ttm_flags, cstate, caching_array, cpages); } r = -ENOMEM; goto out; } list_add(&p->lru, pages); #ifdef CONFIG_HIGHMEM /* gfp flags of highmem page should never be dma32 so we * we should be fine in such case */ if (PageHighMem(p)) continue; #endif for (j = 0; j < npages; ++j) { caching_array[cpages++] = p++; if (cpages == max_cpages) { r = ttm_set_pages_caching(caching_array, cstate, cpages); if (r) { ttm_handle_caching_state_failure(pages, ttm_flags, cstate, caching_array, cpages); goto out; } cpages = 0; } } } if (cpages) { r = ttm_set_pages_caching(caching_array, cstate, cpages); if (r) ttm_handle_caching_state_failure(pages, ttm_flags, cstate, caching_array, cpages); } out: kfree(caching_array); return r; } /** * Fill the given pool if there aren't enough pages and the requested number of * pages is small. */ static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool, int ttm_flags, enum ttm_caching_state cstate, unsigned count, unsigned long *irq_flags) { struct page *p; int r; unsigned cpages = 0; /** * Only allow one pool fill operation at a time. * If pool doesn't have enough pages for the allocation new pages are * allocated from outside of pool. */ if (pool->fill_lock) return; pool->fill_lock = true; /* If allocation request is small and there are not enough * pages in a pool we fill the pool up first. */ if (count < _manager->options.small && count > pool->npages) { struct list_head new_pages; unsigned alloc_size = _manager->options.alloc_size; /** * Can't change page caching if in irqsave context. We have to * drop the pool->lock. */ spin_unlock_irqrestore(&pool->lock, *irq_flags); INIT_LIST_HEAD(&new_pages); r = ttm_alloc_new_pages(&new_pages, pool->gfp_flags, ttm_flags, cstate, alloc_size, 0); spin_lock_irqsave(&pool->lock, *irq_flags); if (!r) { list_splice(&new_pages, &pool->list); ++pool->nrefills; pool->npages += alloc_size; } else { pr_debug("Failed to fill pool (%p)\n", pool); /* If we have any pages left put them to the pool. */ list_for_each_entry(p, &new_pages, lru) { ++cpages; } list_splice(&new_pages, &pool->list); pool->npages += cpages; } } pool->fill_lock = false; } /** * Allocate pages from the pool and put them on the return list. * * @return zero for success or negative error code. */ static int ttm_page_pool_get_pages(struct ttm_page_pool *pool, struct list_head *pages, int ttm_flags, enum ttm_caching_state cstate, unsigned count, unsigned order) { unsigned long irq_flags; struct list_head *p; unsigned i; int r = 0; spin_lock_irqsave(&pool->lock, irq_flags); if (!order) ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count, &irq_flags); if (count >= pool->npages) { /* take all pages from the pool */ list_splice_init(&pool->list, pages); count -= pool->npages; pool->npages = 0; goto out; } /* find the last pages to include for requested number of pages. Split * pool to begin and halve it to reduce search space. */ if (count <= pool->npages/2) { i = 0; list_for_each(p, &pool->list) { if (++i == count) break; } } else { i = pool->npages + 1; list_for_each_prev(p, &pool->list) { if (--i == count) break; } } /* Cut 'count' number of pages from the pool */ list_cut_position(pages, &pool->list, p); pool->npages -= count; count = 0; out: spin_unlock_irqrestore(&pool->lock, irq_flags); /* clear the pages coming from the pool if requested */ if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) { struct page *page; list_for_each_entry(page, pages, lru) { if (PageHighMem(page)) clear_highpage(page); else clear_page(page_address(page)); } } /* If pool didn't have enough pages allocate new one. */ if (count) { gfp_t gfp_flags = pool->gfp_flags; /* set zero flag for page allocation if required */ if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) gfp_flags |= __GFP_ZERO; if (ttm_flags & TTM_PAGE_FLAG_NO_RETRY) gfp_flags |= __GFP_RETRY_MAYFAIL; /* ttm_alloc_new_pages doesn't reference pool so we can run * multiple requests in parallel. **/ r = ttm_alloc_new_pages(pages, gfp_flags, ttm_flags, cstate, count, order); } return r; } /* Put all pages in pages list to correct pool to wait for reuse */ static void ttm_put_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif unsigned long irq_flags; unsigned i; if (pool == NULL) { /* No pool for this memory type so free the pages */ i = 0; while (i < npages) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct page *p = pages[i]; #endif unsigned order = 0, j; if (!pages[i]) { ++i; continue; } #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(flags & TTM_PAGE_FLAG_DMA32) && (npages - i) >= HPAGE_PMD_NR) { for (j = 1; j < HPAGE_PMD_NR; ++j) if (++p != pages[i + j]) break; if (j == HPAGE_PMD_NR) order = HPAGE_PMD_ORDER; } #endif if (page_count(pages[i]) != 1) pr_err("Erroneous page count. Leaking pages.\n"); __free_pages(pages[i], order); j = 1 << order; while (j) { pages[i++] = NULL; --j; } } return; } i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge) { unsigned max_size, n2free; spin_lock_irqsave(&huge->lock, irq_flags); while ((npages - i) >= HPAGE_PMD_NR) { struct page *p = pages[i]; unsigned j; if (!p) break; for (j = 1; j < HPAGE_PMD_NR; ++j) if (++p != pages[i + j]) break; if (j != HPAGE_PMD_NR) break; list_add_tail(&pages[i]->lru, &huge->list); for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = NULL; huge->npages++; } /* Check that we don't go over the pool limit */ max_size = _manager->options.max_size; max_size /= HPAGE_PMD_NR; if (huge->npages > max_size) n2free = huge->npages - max_size; else n2free = 0; spin_unlock_irqrestore(&huge->lock, irq_flags); if (n2free) ttm_page_pool_free(huge, n2free, false); } #endif spin_lock_irqsave(&pool->lock, irq_flags); while (i < npages) { if (pages[i]) { if (page_count(pages[i]) != 1) pr_err("Erroneous page count. Leaking pages.\n"); list_add_tail(&pages[i]->lru, &pool->list); pages[i] = NULL; pool->npages++; } ++i; } /* Check that we don't go over the pool limit */ npages = 0; if (pool->npages > _manager->options.max_size) { npages = pool->npages - _manager->options.max_size; /* free at least NUM_PAGES_TO_ALLOC number of pages * to reduce calls to set_memory_wb */ if (npages < NUM_PAGES_TO_ALLOC) npages = NUM_PAGES_TO_ALLOC; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (npages) ttm_page_pool_free(pool, npages, false); } /* * On success pages list will hold count number of correctly * cached pages. */ static int ttm_get_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif struct list_head plist; struct page *p = NULL; unsigned count, first; int r; /* No pool for cached pages */ if (pool == NULL) { gfp_t gfp_flags = GFP_USER; unsigned i; #ifdef CONFIG_TRANSPARENT_HUGEPAGE unsigned j; #endif /* set zero flag for page allocation if required */ if (flags & TTM_PAGE_FLAG_ZERO_ALLOC) gfp_flags |= __GFP_ZERO; if (flags & TTM_PAGE_FLAG_NO_RETRY) gfp_flags |= __GFP_RETRY_MAYFAIL; if (flags & TTM_PAGE_FLAG_DMA32) gfp_flags |= GFP_DMA32; else gfp_flags |= GFP_HIGHUSER; i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(gfp_flags & GFP_DMA32)) { while (npages >= HPAGE_PMD_NR) { gfp_t huge_flags = gfp_flags; huge_flags |= GFP_TRANSHUGE_LIGHT | __GFP_NORETRY | __GFP_KSWAPD_RECLAIM; huge_flags &= ~__GFP_MOVABLE; huge_flags &= ~__GFP_COMP; p = alloc_pages(huge_flags, HPAGE_PMD_ORDER); if (!p) break; for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = p++; npages -= HPAGE_PMD_NR; } } #endif first = i; while (npages) { p = alloc_page(gfp_flags); if (!p) { pr_debug("Unable to allocate page\n"); return -ENOMEM; } /* Swap the pages if we detect consecutive order */ if (i > first && pages[i - 1] == p - 1) swap(p, pages[i - 1]); pages[i++] = p; --npages; } return 0; } count = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge && npages >= HPAGE_PMD_NR) { INIT_LIST_HEAD(&plist); ttm_page_pool_get_pages(huge, &plist, flags, cstate, npages / HPAGE_PMD_NR, HPAGE_PMD_ORDER); list_for_each_entry(p, &plist, lru) { unsigned j; for (j = 0; j < HPAGE_PMD_NR; ++j) pages[count++] = &p[j]; } } #endif INIT_LIST_HEAD(&plist); r = ttm_page_pool_get_pages(pool, &plist, flags, cstate, npages - count, 0); first = count; list_for_each_entry(p, &plist, lru) { struct page *tmp = p; /* Swap the pages if we detect consecutive order */ if (count > first && pages[count - 1] == tmp - 1) swap(tmp, pages[count - 1]); pages[count++] = tmp; } if (r) { /* If there is any pages in the list put them back to * the pool. */ pr_debug("Failed to allocate extra pages for large request\n"); ttm_put_pages(pages, count, flags, cstate); return r; } return 0; } static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, gfp_t flags, char *name, unsigned int order) { spin_lock_init(&pool->lock); pool->fill_lock = false; INIT_LIST_HEAD(&pool->list); pool->npages = pool->nfrees = 0; pool->gfp_flags = flags; pool->name = name; pool->order = order; } int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages) { int ret; #ifdef CONFIG_TRANSPARENT_HUGEPAGE unsigned order = HPAGE_PMD_ORDER; #else unsigned order = 0; #endif WARN_ON(_manager); pr_info("Initializing pool allocator\n"); _manager = kzalloc(sizeof(*_manager), GFP_KERNEL); if (!_manager) return -ENOMEM; ttm_page_pool_init_locked(&_manager->wc_pool, GFP_HIGHUSER, "wc", 0); ttm_page_pool_init_locked(&_manager->uc_pool, GFP_HIGHUSER, "uc", 0); ttm_page_pool_init_locked(&_manager->wc_pool_dma32, GFP_USER | GFP_DMA32, "wc dma", 0); ttm_page_pool_init_locked(&_manager->uc_pool_dma32, GFP_USER | GFP_DMA32, "uc dma", 0); ttm_page_pool_init_locked(&_manager->wc_pool_huge, (GFP_TRANSHUGE_LIGHT | __GFP_NORETRY | __GFP_KSWAPD_RECLAIM) & ~(__GFP_MOVABLE | __GFP_COMP), "wc huge", order); ttm_page_pool_init_locked(&_manager->uc_pool_huge, (GFP_TRANSHUGE_LIGHT | __GFP_NORETRY | __GFP_KSWAPD_RECLAIM) & ~(__GFP_MOVABLE | __GFP_COMP) , "uc huge", order); _manager->options.max_size = max_pages; _manager->options.small = SMALL_ALLOCATION; _manager->options.alloc_size = NUM_PAGES_TO_ALLOC; ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type, &glob->kobj, "pool"); if (unlikely(ret != 0)) goto error; ret = ttm_pool_mm_shrink_init(_manager); if (unlikely(ret != 0)) goto error; return 0; error: kobject_put(&_manager->kobj); _manager = NULL; return ret; } void ttm_page_alloc_fini(void) { int i; pr_info("Finalizing pool allocator\n"); ttm_pool_mm_shrink_fini(_manager); /* OK to use static buffer since global mutex is no longer used. */ for (i = 0; i < NUM_POOLS; ++i) ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES, true); kobject_put(&_manager->kobj); _manager = NULL; } static void ttm_pool_unpopulate_helper(struct ttm_tt *ttm, unsigned mem_count_update) { struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob; unsigned i; if (mem_count_update == 0) goto put_pages; for (i = 0; i < mem_count_update; ++i) { if (!ttm->pages[i]) continue; ttm_mem_global_free_page(mem_glob, ttm->pages[i], PAGE_SIZE); } put_pages: ttm_put_pages(ttm->pages, ttm->num_pages, ttm->page_flags, ttm->caching_state); ttm->state = tt_unpopulated; } int ttm_pool_populate(struct ttm_tt *ttm, struct ttm_operation_ctx *ctx) { struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob; unsigned i; int ret; if (ttm->state != tt_unpopulated) return 0; if (ttm_check_under_lowerlimit(mem_glob, ttm->num_pages, ctx)) return -ENOMEM; ret = ttm_get_pages(ttm->pages, ttm->num_pages, ttm->page_flags, ttm->caching_state); if (unlikely(ret != 0)) { ttm_pool_unpopulate_helper(ttm, 0); return ret; } for (i = 0; i < ttm->num_pages; ++i) { ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i], PAGE_SIZE, ctx); if (unlikely(ret != 0)) { ttm_pool_unpopulate_helper(ttm, i); return -ENOMEM; } } if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) { ret = ttm_tt_swapin(ttm); if (unlikely(ret != 0)) { ttm_pool_unpopulate(ttm); return ret; } } ttm->state = tt_unbound; return 0; } EXPORT_SYMBOL(ttm_pool_populate); void ttm_pool_unpopulate(struct ttm_tt *ttm) { ttm_pool_unpopulate_helper(ttm, ttm->num_pages); } EXPORT_SYMBOL(ttm_pool_unpopulate); int ttm_populate_and_map_pages(struct device *dev, struct ttm_dma_tt *tt, struct ttm_operation_ctx *ctx) { unsigned i, j; int r; r = ttm_pool_populate(&tt->ttm, ctx); if (r) return r; for (i = 0; i < tt->ttm.num_pages; ++i) { struct page *p = tt->ttm.pages[i]; size_t num_pages = 1; for (j = i + 1; j < tt->ttm.num_pages; ++j) { if (++p != tt->ttm.pages[j]) break; ++num_pages; } tt->dma_address[i] = dma_map_page(dev, tt->ttm.pages[i], 0, num_pages * PAGE_SIZE, DMA_BIDIRECTIONAL); if (dma_mapping_error(dev, tt->dma_address[i])) { while (i--) { dma_unmap_page(dev, tt->dma_address[i], PAGE_SIZE, DMA_BIDIRECTIONAL); tt->dma_address[i] = 0; } ttm_pool_unpopulate(&tt->ttm); return -EFAULT; } for (j = 1; j < num_pages; ++j) { tt->dma_address[i + 1] = tt->dma_address[i] + PAGE_SIZE; ++i; } } return 0; } EXPORT_SYMBOL(ttm_populate_and_map_pages); void ttm_unmap_and_unpopulate_pages(struct device *dev, struct ttm_dma_tt *tt) { unsigned i, j; for (i = 0; i < tt->ttm.num_pages;) { struct page *p = tt->ttm.pages[i]; size_t num_pages = 1; if (!tt->dma_address[i] || !tt->ttm.pages[i]) { ++i; continue; } for (j = i + 1; j < tt->ttm.num_pages; ++j) { if (++p != tt->ttm.pages[j]) break; ++num_pages; } dma_unmap_page(dev, tt->dma_address[i], num_pages * PAGE_SIZE, DMA_BIDIRECTIONAL); i += num_pages; } ttm_pool_unpopulate(&tt->ttm); } EXPORT_SYMBOL(ttm_unmap_and_unpopulate_pages); int ttm_page_alloc_debugfs(struct seq_file *m, void *data) { struct ttm_page_pool *p; unsigned i; char *h[] = {"pool", "refills", "pages freed", "size"}; if (!_manager) { seq_printf(m, "No pool allocator running.\n"); return 0; } seq_printf(m, "%7s %12s %13s %8s\n", h[0], h[1], h[2], h[3]); for (i = 0; i < NUM_POOLS; ++i) { p = &_manager->pools[i]; seq_printf(m, "%7s %12ld %13ld %8d\n", p->name, p->nrefills, p->nfrees, p->npages); } return 0; } EXPORT_SYMBOL(ttm_page_alloc_debugfs);
./CrossVul/dataset_final_sorted/CWE-125/c/good_1328_0
crossvul-cpp_data_bad_4856_1
/* $Id$ */ /* * Copyright (c) 1997 Greg Ward Larson * Copyright (c) 1997 Silicon Graphics, Inc. * * 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, Greg Larson 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, Greg Larson 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, GREG LARSON 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 "tiffiop.h" #ifdef LOGLUV_SUPPORT /* * TIFF Library. * LogLuv compression support for high dynamic range images. * * Contributed by Greg Larson. * * LogLuv image support uses the TIFF library to store 16 or 10-bit * log luminance values with 8 bits each of u and v or a 14-bit index. * * The codec can take as input and produce as output 32-bit IEEE float values * as well as 16-bit integer values. A 16-bit luminance is interpreted * as a sign bit followed by a 15-bit integer that is converted * to and from a linear magnitude using the transformation: * * L = 2^( (Le+.5)/256 - 64 ) # real from 15-bit * * Le = floor( 256*(log2(L) + 64) ) # 15-bit from real * * The actual conversion to world luminance units in candelas per sq. meter * requires an additional multiplier, which is stored in the TIFFTAG_STONITS. * This value is usually set such that a reasonable exposure comes from * clamping decoded luminances above 1 to 1 in the displayed image. * * The 16-bit values for u and v may be converted to real values by dividing * each by 32768. (This allows for negative values, which aren't useful as * far as we know, but are left in case of future improvements in human * color vision.) * * Conversion from (u,v), which is actually the CIE (u',v') system for * you color scientists, is accomplished by the following transformation: * * u = 4*x / (-2*x + 12*y + 3) * v = 9*y / (-2*x + 12*y + 3) * * x = 9*u / (6*u - 16*v + 12) * y = 4*v / (6*u - 16*v + 12) * * This process is greatly simplified by passing 32-bit IEEE floats * for each of three CIE XYZ coordinates. The codec then takes care * of conversion to and from LogLuv, though the application is still * responsible for interpreting the TIFFTAG_STONITS calibration factor. * * By definition, a CIE XYZ vector of [1 1 1] corresponds to a neutral white * point of (x,y)=(1/3,1/3). However, most color systems assume some other * white point, such as D65, and an absolute color conversion to XYZ then * to another color space with a different white point may introduce an * unwanted color cast to the image. It is often desirable, therefore, to * perform a white point conversion that maps the input white to [1 1 1] * in XYZ, then record the original white point using the TIFFTAG_WHITEPOINT * tag value. A decoder that demands absolute color calibration may use * this white point tag to get back the original colors, but usually it * will be ignored and the new white point will be used instead that * matches the output color space. * * Pixel information is compressed into one of two basic encodings, depending * on the setting of the compression tag, which is one of COMPRESSION_SGILOG * or COMPRESSION_SGILOG24. For COMPRESSION_SGILOG, greyscale data is * stored as: * * 1 15 * |-+---------------| * * COMPRESSION_SGILOG color data is stored as: * * 1 15 8 8 * |-+---------------|--------+--------| * S Le ue ve * * For the 24-bit COMPRESSION_SGILOG24 color format, the data is stored as: * * 10 14 * |----------|--------------| * Le' Ce * * There is no sign bit in the 24-bit case, and the (u,v) chromaticity is * encoded as an index for optimal color resolution. The 10 log bits are * defined by the following conversions: * * L = 2^((Le'+.5)/64 - 12) # real from 10-bit * * Le' = floor( 64*(log2(L) + 12) ) # 10-bit from real * * The 10 bits of the smaller format may be converted into the 15 bits of * the larger format by multiplying by 4 and adding 13314. Obviously, * a smaller range of magnitudes is covered (about 5 orders of magnitude * instead of 38), and the lack of a sign bit means that negative luminances * are not allowed. (Well, they aren't allowed in the real world, either, * but they are useful for certain types of image processing.) * * The desired user format is controlled by the setting the internal * pseudo tag TIFFTAG_SGILOGDATAFMT to one of: * SGILOGDATAFMT_FLOAT = IEEE 32-bit float XYZ values * SGILOGDATAFMT_16BIT = 16-bit integer encodings of logL, u and v * Raw data i/o is also possible using: * SGILOGDATAFMT_RAW = 32-bit unsigned integer with encoded pixel * In addition, the following decoding is provided for ease of display: * SGILOGDATAFMT_8BIT = 8-bit default RGB gamma-corrected values * * For grayscale images, we provide the following data formats: * SGILOGDATAFMT_FLOAT = IEEE 32-bit float Y values * SGILOGDATAFMT_16BIT = 16-bit integer w/ encoded luminance * SGILOGDATAFMT_8BIT = 8-bit gray monitor values * * Note that the COMPRESSION_SGILOG applies a simple run-length encoding * scheme by separating the logL, u and v bytes for each row and applying * a PackBits type of compression. Since the 24-bit encoding is not * adaptive, the 32-bit color format takes less space in many cases. * * Further control is provided over the conversion from higher-resolution * formats to final encoded values through the pseudo tag * TIFFTAG_SGILOGENCODE: * SGILOGENCODE_NODITHER = do not dither encoded values * SGILOGENCODE_RANDITHER = apply random dithering during encoding * * The default value of this tag is SGILOGENCODE_NODITHER for * COMPRESSION_SGILOG to maximize run-length encoding and * SGILOGENCODE_RANDITHER for COMPRESSION_SGILOG24 to turn * quantization errors into noise. */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* * State block for each open TIFF * file using LogLuv compression/decompression. */ typedef struct logLuvState LogLuvState; struct logLuvState { int user_datafmt; /* user data format */ int encode_meth; /* encoding method */ int pixel_size; /* bytes per pixel */ uint8* tbuf; /* translation buffer */ tmsize_t tbuflen; /* buffer length */ void (*tfunc)(LogLuvState*, uint8*, tmsize_t); TIFFVSetMethod vgetparent; /* super-class method */ TIFFVSetMethod vsetparent; /* super-class method */ }; #define DecoderState(tif) ((LogLuvState*) (tif)->tif_data) #define EncoderState(tif) ((LogLuvState*) (tif)->tif_data) #define SGILOGDATAFMT_UNKNOWN -1 #define MINRUN 4 /* minimum run length */ /* * Decode a string of 16-bit gray pixels. */ static int LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "LogL16Decode"; LogLuvState* sp = DecoderState(tif); int shft; tmsize_t i; tmsize_t npixels; unsigned char* bp; int16* tp; int16 b; tmsize_t cc; int rc; assert(s == 0); assert(sp != NULL); npixels = occ / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_16BIT) tp = (int16*) op; else { if(sp->tbuflen < npixels) { TIFFErrorExt(tif->tif_clientdata, module, "Translation buffer too short"); return (0); } tp = (int16*) sp->tbuf; } _TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0])); bp = (unsigned char*) tif->tif_rawcp; cc = tif->tif_rawcc; /* get each byte string */ for (shft = 2*8; (shft -= 8) >= 0; ) { for (i = 0; i < npixels && cc > 0; ) { if (*bp >= 128) { /* run */ if( cc < 2 ) break; rc = *bp++ + (2-128); b = (int16)(*bp++ << shft); cc -= 2; while (rc-- && i < npixels) tp[i++] |= b; } else { /* non-run */ rc = *bp++; /* nul is noop */ while (--cc && rc-- && i < npixels) tp[i++] |= (int16)*bp++ << shft; } } if (i != npixels) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at row %lu (short %I64d pixels)", (unsigned long) tif->tif_row, (unsigned __int64) (npixels - i)); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at row %lu (short %llu pixels)", (unsigned long) tif->tif_row, (unsigned long long) (npixels - i)); #endif tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (0); } } (*sp->tfunc)(sp, op, npixels); tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); } /* * Decode a string of 24-bit pixels. */ static int LogLuvDecode24(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "LogLuvDecode24"; LogLuvState* sp = DecoderState(tif); tmsize_t cc; tmsize_t i; tmsize_t npixels; unsigned char* bp; uint32* tp; assert(s == 0); assert(sp != NULL); npixels = occ / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_RAW) tp = (uint32 *)op; else { if(sp->tbuflen < npixels) { TIFFErrorExt(tif->tif_clientdata, module, "Translation buffer too short"); return (0); } tp = (uint32 *) sp->tbuf; } /* copy to array of uint32 */ bp = (unsigned char*) tif->tif_rawcp; cc = tif->tif_rawcc; for (i = 0; i < npixels && cc >= 3; i++) { tp[i] = bp[0] << 16 | bp[1] << 8 | bp[2]; bp += 3; cc -= 3; } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; if (i != npixels) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at row %lu (short %I64d pixels)", (unsigned long) tif->tif_row, (unsigned __int64) (npixels - i)); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at row %lu (short %llu pixels)", (unsigned long) tif->tif_row, (unsigned long long) (npixels - i)); #endif return (0); } (*sp->tfunc)(sp, op, npixels); return (1); } /* * Decode a string of 32-bit pixels. */ static int LogLuvDecode32(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "LogLuvDecode32"; LogLuvState* sp; int shft; tmsize_t i; tmsize_t npixels; unsigned char* bp; uint32* tp; uint32 b; tmsize_t cc; int rc; assert(s == 0); sp = DecoderState(tif); assert(sp != NULL); npixels = occ / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_RAW) tp = (uint32*) op; else { if(sp->tbuflen < npixels) { TIFFErrorExt(tif->tif_clientdata, module, "Translation buffer too short"); return (0); } tp = (uint32*) sp->tbuf; } _TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0])); bp = (unsigned char*) tif->tif_rawcp; cc = tif->tif_rawcc; /* get each byte string */ for (shft = 4*8; (shft -= 8) >= 0; ) { for (i = 0; i < npixels && cc > 0; ) { if (*bp >= 128) { /* run */ if( cc < 2 ) break; rc = *bp++ + (2-128); b = (uint32)*bp++ << shft; cc -= 2; while (rc-- && i < npixels) tp[i++] |= b; } else { /* non-run */ rc = *bp++; /* nul is noop */ while (--cc && rc-- && i < npixels) tp[i++] |= (uint32)*bp++ << shft; } } if (i != npixels) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at row %lu (short %I64d pixels)", (unsigned long) tif->tif_row, (unsigned __int64) (npixels - i)); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at row %lu (short %llu pixels)", (unsigned long) tif->tif_row, (unsigned long long) (npixels - i)); #endif tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (0); } } (*sp->tfunc)(sp, op, npixels); tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); } /* * Decode a strip of pixels. We break it into rows to * maintain synchrony with the encode algorithm, which * is row by row. */ static int LogLuvDecodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { tmsize_t rowlen = TIFFScanlineSize(tif); if (rowlen == 0) return 0; assert(cc%rowlen == 0); while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) { bp += rowlen; cc -= rowlen; } return (cc == 0); } /* * Decode a tile of pixels. We break it into rows to * maintain synchrony with the encode algorithm, which * is row by row. */ static int LogLuvDecodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { tmsize_t rowlen = TIFFTileRowSize(tif); if (rowlen == 0) return 0; assert(cc%rowlen == 0); while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s)) { bp += rowlen; cc -= rowlen; } return (cc == 0); } /* * Encode a row of 16-bit pixels. */ static int LogL16Encode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "LogL16Encode"; LogLuvState* sp = EncoderState(tif); int shft; tmsize_t i; tmsize_t j; tmsize_t npixels; uint8* op; int16* tp; int16 b; tmsize_t occ; int rc=0, mask; tmsize_t beg; assert(s == 0); assert(sp != NULL); npixels = cc / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_16BIT) tp = (int16*) bp; else { tp = (int16*) sp->tbuf; if(sp->tbuflen < npixels) { TIFFErrorExt(tif->tif_clientdata, module, "Translation buffer too short"); return (0); } (*sp->tfunc)(sp, bp, npixels); } /* compress each byte string */ op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; for (shft = 2*8; (shft -= 8) >= 0; ) for (i = 0; i < npixels; i += rc) { if (occ < 4) { tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; if (!TIFFFlushData1(tif)) return (-1); op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; } mask = 0xff << shft; /* find next run */ for (beg = i; beg < npixels; beg += rc) { b = (int16) (tp[beg] & mask); rc = 1; while (rc < 127+2 && beg+rc < npixels && (tp[beg+rc] & mask) == b) rc++; if (rc >= MINRUN) break; /* long enough */ } if (beg-i > 1 && beg-i < MINRUN) { b = (int16) (tp[i] & mask);/*check short run */ j = i+1; while ((tp[j++] & mask) == b) if (j == beg) { *op++ = (uint8)(128-2+j-i); *op++ = (uint8)(b >> shft); occ -= 2; i = beg; break; } } while (i < beg) { /* write out non-run */ if ((j = beg-i) > 127) j = 127; if (occ < j+3) { tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; if (!TIFFFlushData1(tif)) return (-1); op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; } *op++ = (uint8) j; occ--; while (j--) { *op++ = (uint8) (tp[i++] >> shft & 0xff); occ--; } } if (rc >= MINRUN) { /* write out run */ *op++ = (uint8) (128-2+rc); *op++ = (uint8) (tp[beg] >> shft & 0xff); occ -= 2; } else rc = 0; } tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; return (1); } /* * Encode a row of 24-bit pixels. */ static int LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "LogLuvEncode24"; LogLuvState* sp = EncoderState(tif); tmsize_t i; tmsize_t npixels; tmsize_t occ; uint8* op; uint32* tp; assert(s == 0); assert(sp != NULL); npixels = cc / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_RAW) tp = (uint32*) bp; else { tp = (uint32*) sp->tbuf; if(sp->tbuflen < npixels) { TIFFErrorExt(tif->tif_clientdata, module, "Translation buffer too short"); return (0); } (*sp->tfunc)(sp, bp, npixels); } /* write out encoded pixels */ op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; for (i = npixels; i--; ) { if (occ < 3) { tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; if (!TIFFFlushData1(tif)) return (-1); op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; } *op++ = (uint8)(*tp >> 16); *op++ = (uint8)(*tp >> 8 & 0xff); *op++ = (uint8)(*tp++ & 0xff); occ -= 3; } tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; return (1); } /* * Encode a row of 32-bit pixels. */ static int LogLuvEncode32(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "LogLuvEncode32"; LogLuvState* sp = EncoderState(tif); int shft; tmsize_t i; tmsize_t j; tmsize_t npixels; uint8* op; uint32* tp; uint32 b; tmsize_t occ; int rc=0, mask; tmsize_t beg; assert(s == 0); assert(sp != NULL); npixels = cc / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_RAW) tp = (uint32*) bp; else { tp = (uint32*) sp->tbuf; if(sp->tbuflen < npixels) { TIFFErrorExt(tif->tif_clientdata, module, "Translation buffer too short"); return (0); } (*sp->tfunc)(sp, bp, npixels); } /* compress each byte string */ op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; for (shft = 4*8; (shft -= 8) >= 0; ) for (i = 0; i < npixels; i += rc) { if (occ < 4) { tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; if (!TIFFFlushData1(tif)) return (-1); op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; } mask = 0xff << shft; /* find next run */ for (beg = i; beg < npixels; beg += rc) { b = tp[beg] & mask; rc = 1; while (rc < 127+2 && beg+rc < npixels && (tp[beg+rc] & mask) == b) rc++; if (rc >= MINRUN) break; /* long enough */ } if (beg-i > 1 && beg-i < MINRUN) { b = tp[i] & mask; /* check short run */ j = i+1; while ((tp[j++] & mask) == b) if (j == beg) { *op++ = (uint8)(128-2+j-i); *op++ = (uint8)(b >> shft); occ -= 2; i = beg; break; } } while (i < beg) { /* write out non-run */ if ((j = beg-i) > 127) j = 127; if (occ < j+3) { tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; if (!TIFFFlushData1(tif)) return (-1); op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; } *op++ = (uint8) j; occ--; while (j--) { *op++ = (uint8)(tp[i++] >> shft & 0xff); occ--; } } if (rc >= MINRUN) { /* write out run */ *op++ = (uint8) (128-2+rc); *op++ = (uint8)(tp[beg] >> shft & 0xff); occ -= 2; } else rc = 0; } tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; return (1); } /* * Encode a strip of pixels. We break it into rows to * avoid encoding runs across row boundaries. */ static int LogLuvEncodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { tmsize_t rowlen = TIFFScanlineSize(tif); if (rowlen == 0) return 0; assert(cc%rowlen == 0); while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) { bp += rowlen; cc -= rowlen; } return (cc == 0); } /* * Encode a tile of pixels. We break it into rows to * avoid encoding runs across row boundaries. */ static int LogLuvEncodeTile(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { tmsize_t rowlen = TIFFTileRowSize(tif); if (rowlen == 0) return 0; assert(cc%rowlen == 0); while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) { bp += rowlen; cc -= rowlen; } return (cc == 0); } /* * Encode/Decode functions for converting to and from user formats. */ #include "uvcode.h" #ifndef UVSCALE #define U_NEU 0.210526316 #define V_NEU 0.473684211 #define UVSCALE 410. #endif #ifndef M_LN2 #define M_LN2 0.69314718055994530942 #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #undef log2 /* Conflict with C'99 function */ #define log2(x) ((1./M_LN2)*log(x)) #undef exp2 /* Conflict with C'99 function */ #define exp2(x) exp(M_LN2*(x)) #define itrunc(x,m) ((m)==SGILOGENCODE_NODITHER ? \ (int)(x) : \ (int)((x) + rand()*(1./RAND_MAX) - .5)) #if !LOGLUV_PUBLIC static #endif double LogL16toY(int p16) /* compute luminance from 16-bit LogL */ { int Le = p16 & 0x7fff; double Y; if (!Le) return (0.); Y = exp(M_LN2/256.*(Le+.5) - M_LN2*64.); return (!(p16 & 0x8000) ? Y : -Y); } #if !LOGLUV_PUBLIC static #endif int LogL16fromY(double Y, int em) /* get 16-bit LogL from Y */ { if (Y >= 1.8371976e19) return (0x7fff); if (Y <= -1.8371976e19) return (0xffff); if (Y > 5.4136769e-20) return itrunc(256.*(log2(Y) + 64.), em); if (Y < -5.4136769e-20) return (~0x7fff | itrunc(256.*(log2(-Y) + 64.), em)); return (0); } static void L16toY(LogLuvState* sp, uint8* op, tmsize_t n) { int16* l16 = (int16*) sp->tbuf; float* yp = (float*) op; while (n-- > 0) *yp++ = (float)LogL16toY(*l16++); } static void L16toGry(LogLuvState* sp, uint8* op, tmsize_t n) { int16* l16 = (int16*) sp->tbuf; uint8* gp = (uint8*) op; while (n-- > 0) { double Y = LogL16toY(*l16++); *gp++ = (uint8) ((Y <= 0.) ? 0 : (Y >= 1.) ? 255 : (int)(256.*sqrt(Y))); } } static void L16fromY(LogLuvState* sp, uint8* op, tmsize_t n) { int16* l16 = (int16*) sp->tbuf; float* yp = (float*) op; while (n-- > 0) *l16++ = (int16) (LogL16fromY(*yp++, sp->encode_meth)); } #if !LOGLUV_PUBLIC static #endif void XYZtoRGB24(float xyz[3], uint8 rgb[3]) { double r, g, b; /* assume CCIR-709 primaries */ r = 2.690*xyz[0] + -1.276*xyz[1] + -0.414*xyz[2]; g = -1.022*xyz[0] + 1.978*xyz[1] + 0.044*xyz[2]; b = 0.061*xyz[0] + -0.224*xyz[1] + 1.163*xyz[2]; /* assume 2.0 gamma for speed */ /* could use integer sqrt approx., but this is probably faster */ rgb[0] = (uint8)((r<=0.) ? 0 : (r >= 1.) ? 255 : (int)(256.*sqrt(r))); rgb[1] = (uint8)((g<=0.) ? 0 : (g >= 1.) ? 255 : (int)(256.*sqrt(g))); rgb[2] = (uint8)((b<=0.) ? 0 : (b >= 1.) ? 255 : (int)(256.*sqrt(b))); } #if !LOGLUV_PUBLIC static #endif double LogL10toY(int p10) /* compute luminance from 10-bit LogL */ { if (p10 == 0) return (0.); return (exp(M_LN2/64.*(p10+.5) - M_LN2*12.)); } #if !LOGLUV_PUBLIC static #endif int LogL10fromY(double Y, int em) /* get 10-bit LogL from Y */ { if (Y >= 15.742) return (0x3ff); else if (Y <= .00024283) return (0); else return itrunc(64.*(log2(Y) + 12.), em); } #define NANGLES 100 #define uv2ang(u, v) ( (NANGLES*.499999999/M_PI) \ * atan2((v)-V_NEU,(u)-U_NEU) + .5*NANGLES ) static int oog_encode(double u, double v) /* encode out-of-gamut chroma */ { static int oog_table[NANGLES]; static int initialized = 0; register int i; if (!initialized) { /* set up perimeter table */ double eps[NANGLES], ua, va, ang, epsa; int ui, vi, ustep; for (i = NANGLES; i--; ) eps[i] = 2.; for (vi = UV_NVS; vi--; ) { va = UV_VSTART + (vi+.5)*UV_SQSIZ; ustep = uv_row[vi].nus-1; if (vi == UV_NVS-1 || vi == 0 || ustep <= 0) ustep = 1; for (ui = uv_row[vi].nus-1; ui >= 0; ui -= ustep) { ua = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ; ang = uv2ang(ua, va); i = (int) ang; epsa = fabs(ang - (i+.5)); if (epsa < eps[i]) { oog_table[i] = uv_row[vi].ncum + ui; eps[i] = epsa; } } } for (i = NANGLES; i--; ) /* fill any holes */ if (eps[i] > 1.5) { int i1, i2; for (i1 = 1; i1 < NANGLES/2; i1++) if (eps[(i+i1)%NANGLES] < 1.5) break; for (i2 = 1; i2 < NANGLES/2; i2++) if (eps[(i+NANGLES-i2)%NANGLES] < 1.5) break; if (i1 < i2) oog_table[i] = oog_table[(i+i1)%NANGLES]; else oog_table[i] = oog_table[(i+NANGLES-i2)%NANGLES]; } initialized = 1; } i = (int) uv2ang(u, v); /* look up hue angle */ return (oog_table[i]); } #undef uv2ang #undef NANGLES #if !LOGLUV_PUBLIC static #endif int uv_encode(double u, double v, int em) /* encode (u',v') coordinates */ { register int vi, ui; if (v < UV_VSTART) return oog_encode(u, v); vi = itrunc((v - UV_VSTART)*(1./UV_SQSIZ), em); if (vi >= UV_NVS) return oog_encode(u, v); if (u < uv_row[vi].ustart) return oog_encode(u, v); ui = itrunc((u - uv_row[vi].ustart)*(1./UV_SQSIZ), em); if (ui >= uv_row[vi].nus) return oog_encode(u, v); return (uv_row[vi].ncum + ui); } #if !LOGLUV_PUBLIC static #endif int uv_decode(double *up, double *vp, int c) /* decode (u',v') index */ { int upper, lower; register int ui, vi; if (c < 0 || c >= UV_NDIVS) return (-1); lower = 0; /* binary search */ upper = UV_NVS; while (upper - lower > 1) { vi = (lower + upper) >> 1; ui = c - uv_row[vi].ncum; if (ui > 0) lower = vi; else if (ui < 0) upper = vi; else { lower = vi; break; } } vi = lower; ui = c - uv_row[vi].ncum; *up = uv_row[vi].ustart + (ui+.5)*UV_SQSIZ; *vp = UV_VSTART + (vi+.5)*UV_SQSIZ; return (0); } #if !LOGLUV_PUBLIC static #endif void LogLuv24toXYZ(uint32 p, float XYZ[3]) { int Ce; double L, u, v, s, x, y; /* decode luminance */ L = LogL10toY(p>>14 & 0x3ff); if (L <= 0.) { XYZ[0] = XYZ[1] = XYZ[2] = 0.; return; } /* decode color */ Ce = p & 0x3fff; if (uv_decode(&u, &v, Ce) < 0) { u = U_NEU; v = V_NEU; } s = 1./(6.*u - 16.*v + 12.); x = 9.*u * s; y = 4.*v * s; /* convert to XYZ */ XYZ[0] = (float)(x/y * L); XYZ[1] = (float)L; XYZ[2] = (float)((1.-x-y)/y * L); } #if !LOGLUV_PUBLIC static #endif uint32 LogLuv24fromXYZ(float XYZ[3], int em) { int Le, Ce; double u, v, s; /* encode luminance */ Le = LogL10fromY(XYZ[1], em); /* encode color */ s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2]; if (!Le || s <= 0.) { u = U_NEU; v = V_NEU; } else { u = 4.*XYZ[0] / s; v = 9.*XYZ[1] / s; } Ce = uv_encode(u, v, em); if (Ce < 0) /* never happens */ Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER); /* combine encodings */ return (Le << 14 | Ce); } static void Luv24toXYZ(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; float* xyz = (float*) op; while (n-- > 0) { LogLuv24toXYZ(*luv, xyz); xyz += 3; luv++; } } static void Luv24toLuv48(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; int16* luv3 = (int16*) op; while (n-- > 0) { double u, v; *luv3++ = (int16)((*luv >> 12 & 0xffd) + 13314); if (uv_decode(&u, &v, *luv&0x3fff) < 0) { u = U_NEU; v = V_NEU; } *luv3++ = (int16)(u * (1L<<15)); *luv3++ = (int16)(v * (1L<<15)); luv++; } } static void Luv24toRGB(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; uint8* rgb = (uint8*) op; while (n-- > 0) { float xyz[3]; LogLuv24toXYZ(*luv++, xyz); XYZtoRGB24(xyz, rgb); rgb += 3; } } static void Luv24fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; float* xyz = (float*) op; while (n-- > 0) { *luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth); xyz += 3; } } static void Luv24fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; int16* luv3 = (int16*) op; while (n-- > 0) { int Le, Ce; if (luv3[0] <= 0) Le = 0; else if (luv3[0] >= (1<<12)+3314) Le = (1<<10) - 1; else if (sp->encode_meth == SGILOGENCODE_NODITHER) Le = (luv3[0]-3314) >> 2; else Le = itrunc(.25*(luv3[0]-3314.), sp->encode_meth); Ce = uv_encode((luv3[1]+.5)/(1<<15), (luv3[2]+.5)/(1<<15), sp->encode_meth); if (Ce < 0) /* never happens */ Ce = uv_encode(U_NEU, V_NEU, SGILOGENCODE_NODITHER); *luv++ = (uint32)Le << 14 | Ce; luv3 += 3; } } #if !LOGLUV_PUBLIC static #endif void LogLuv32toXYZ(uint32 p, float XYZ[3]) { double L, u, v, s, x, y; /* decode luminance */ L = LogL16toY((int)p >> 16); if (L <= 0.) { XYZ[0] = XYZ[1] = XYZ[2] = 0.; return; } /* decode color */ u = 1./UVSCALE * ((p>>8 & 0xff) + .5); v = 1./UVSCALE * ((p & 0xff) + .5); s = 1./(6.*u - 16.*v + 12.); x = 9.*u * s; y = 4.*v * s; /* convert to XYZ */ XYZ[0] = (float)(x/y * L); XYZ[1] = (float)L; XYZ[2] = (float)((1.-x-y)/y * L); } #if !LOGLUV_PUBLIC static #endif uint32 LogLuv32fromXYZ(float XYZ[3], int em) { unsigned int Le, ue, ve; double u, v, s; /* encode luminance */ Le = (unsigned int)LogL16fromY(XYZ[1], em); /* encode color */ s = XYZ[0] + 15.*XYZ[1] + 3.*XYZ[2]; if (!Le || s <= 0.) { u = U_NEU; v = V_NEU; } else { u = 4.*XYZ[0] / s; v = 9.*XYZ[1] / s; } if (u <= 0.) ue = 0; else ue = itrunc(UVSCALE*u, em); if (ue > 255) ue = 255; if (v <= 0.) ve = 0; else ve = itrunc(UVSCALE*v, em); if (ve > 255) ve = 255; /* combine encodings */ return (Le << 16 | ue << 8 | ve); } static void Luv32toXYZ(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; float* xyz = (float*) op; while (n-- > 0) { LogLuv32toXYZ(*luv++, xyz); xyz += 3; } } static void Luv32toLuv48(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; int16* luv3 = (int16*) op; while (n-- > 0) { double u, v; *luv3++ = (int16)(*luv >> 16); u = 1./UVSCALE * ((*luv>>8 & 0xff) + .5); v = 1./UVSCALE * ((*luv & 0xff) + .5); *luv3++ = (int16)(u * (1L<<15)); *luv3++ = (int16)(v * (1L<<15)); luv++; } } static void Luv32toRGB(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; uint8* rgb = (uint8*) op; while (n-- > 0) { float xyz[3]; LogLuv32toXYZ(*luv++, xyz); XYZtoRGB24(xyz, rgb); rgb += 3; } } static void Luv32fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; float* xyz = (float*) op; while (n-- > 0) { *luv++ = LogLuv32fromXYZ(xyz, sp->encode_meth); xyz += 3; } } static void Luv32fromLuv48(LogLuvState* sp, uint8* op, tmsize_t n) { uint32* luv = (uint32*) sp->tbuf; int16* luv3 = (int16*) op; if (sp->encode_meth == SGILOGENCODE_NODITHER) { while (n-- > 0) { *luv++ = (uint32)luv3[0] << 16 | (luv3[1]*(uint32)(UVSCALE+.5) >> 7 & 0xff00) | (luv3[2]*(uint32)(UVSCALE+.5) >> 15 & 0xff); luv3 += 3; } return; } while (n-- > 0) { *luv++ = (uint32)luv3[0] << 16 | (itrunc(luv3[1]*(UVSCALE/(1<<15)), sp->encode_meth) << 8 & 0xff00) | (itrunc(luv3[2]*(UVSCALE/(1<<15)), sp->encode_meth) & 0xff); luv3 += 3; } } static void _logLuvNop(LogLuvState* sp, uint8* op, tmsize_t n) { (void) sp; (void) op; (void) n; } static int LogL16GuessDataFmt(TIFFDirectory *td) { #define PACK(s,b,f) (((b)<<6)|((s)<<3)|(f)) switch (PACK(td->td_samplesperpixel, td->td_bitspersample, td->td_sampleformat)) { case PACK(1, 32, SAMPLEFORMAT_IEEEFP): return (SGILOGDATAFMT_FLOAT); case PACK(1, 16, SAMPLEFORMAT_VOID): case PACK(1, 16, SAMPLEFORMAT_INT): case PACK(1, 16, SAMPLEFORMAT_UINT): return (SGILOGDATAFMT_16BIT); case PACK(1, 8, SAMPLEFORMAT_VOID): case PACK(1, 8, SAMPLEFORMAT_UINT): return (SGILOGDATAFMT_8BIT); } #undef PACK return (SGILOGDATAFMT_UNKNOWN); } static tmsize_t multiply_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 * m2; if (m1 && bytes / m1 != m2) bytes = 0; return bytes; } static int LogL16InitState(TIFF* tif) { static const char module[] = "LogL16InitState"; TIFFDirectory *td = &tif->tif_dir; LogLuvState* sp = DecoderState(tif); assert(sp != NULL); assert(td->td_photometric == PHOTOMETRIC_LOGL); if( td->td_samplesperpixel != 1 ) { TIFFErrorExt(tif->tif_clientdata, module, "Sorry, can not handle LogL image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } /* for some reason, we can't do this in TIFFInitLogL16 */ if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN) sp->user_datafmt = LogL16GuessDataFmt(td); switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->pixel_size = sizeof (float); break; case SGILOGDATAFMT_16BIT: sp->pixel_size = sizeof (int16); break; case SGILOGDATAFMT_8BIT: sp->pixel_size = sizeof (uint8); break; default: TIFFErrorExt(tif->tif_clientdata, module, "No support for converting user data format to LogL"); return (0); } if( isTiled(tif) ) sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength); else sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip); if (multiply_ms(sp->tbuflen, sizeof (int16)) == 0 || (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (int16))) == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer"); return (0); } return (1); } static int LogLuvGuessDataFmt(TIFFDirectory *td) { int guess; /* * If the user didn't tell us their datafmt, * take our best guess from the bitspersample. */ #define PACK(a,b) (((a)<<3)|(b)) switch (PACK(td->td_bitspersample, td->td_sampleformat)) { case PACK(32, SAMPLEFORMAT_IEEEFP): guess = SGILOGDATAFMT_FLOAT; break; case PACK(32, SAMPLEFORMAT_VOID): case PACK(32, SAMPLEFORMAT_UINT): case PACK(32, SAMPLEFORMAT_INT): guess = SGILOGDATAFMT_RAW; break; case PACK(16, SAMPLEFORMAT_VOID): case PACK(16, SAMPLEFORMAT_INT): case PACK(16, SAMPLEFORMAT_UINT): guess = SGILOGDATAFMT_16BIT; break; case PACK( 8, SAMPLEFORMAT_VOID): case PACK( 8, SAMPLEFORMAT_UINT): guess = SGILOGDATAFMT_8BIT; break; default: guess = SGILOGDATAFMT_UNKNOWN; break; #undef PACK } /* * Double-check samples per pixel. */ switch (td->td_samplesperpixel) { case 1: if (guess != SGILOGDATAFMT_RAW) guess = SGILOGDATAFMT_UNKNOWN; break; case 3: if (guess == SGILOGDATAFMT_RAW) guess = SGILOGDATAFMT_UNKNOWN; break; default: guess = SGILOGDATAFMT_UNKNOWN; break; } return (guess); } static int LogLuvInitState(TIFF* tif) { static const char module[] = "LogLuvInitState"; TIFFDirectory* td = &tif->tif_dir; LogLuvState* sp = DecoderState(tif); assert(sp != NULL); assert(td->td_photometric == PHOTOMETRIC_LOGLUV); /* for some reason, we can't do this in TIFFInitLogLuv */ if (td->td_planarconfig != PLANARCONFIG_CONTIG) { TIFFErrorExt(tif->tif_clientdata, module, "SGILog compression cannot handle non-contiguous data"); return (0); } if (sp->user_datafmt == SGILOGDATAFMT_UNKNOWN) sp->user_datafmt = LogLuvGuessDataFmt(td); switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->pixel_size = 3*sizeof (float); break; case SGILOGDATAFMT_16BIT: sp->pixel_size = 3*sizeof (int16); break; case SGILOGDATAFMT_RAW: sp->pixel_size = sizeof (uint32); break; case SGILOGDATAFMT_8BIT: sp->pixel_size = 3*sizeof (uint8); break; default: TIFFErrorExt(tif->tif_clientdata, module, "No support for converting user data format to LogLuv"); return (0); } if( isTiled(tif) ) sp->tbuflen = multiply_ms(td->td_tilewidth, td->td_tilelength); else sp->tbuflen = multiply_ms(td->td_imagewidth, td->td_rowsperstrip); if (multiply_ms(sp->tbuflen, sizeof (uint32)) == 0 || (sp->tbuf = (uint8*) _TIFFmalloc(sp->tbuflen * sizeof (uint32))) == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for SGILog translation buffer"); return (0); } return (1); } static int LogLuvFixupTags(TIFF* tif) { (void) tif; return (1); } static int LogLuvSetupDecode(TIFF* tif) { static const char module[] = "LogLuvSetupDecode"; LogLuvState* sp = DecoderState(tif); TIFFDirectory* td = &tif->tif_dir; tif->tif_postdecode = _TIFFNoPostDecode; switch (td->td_photometric) { case PHOTOMETRIC_LOGLUV: if (!LogLuvInitState(tif)) break; if (td->td_compression == COMPRESSION_SGILOG24) { tif->tif_decoderow = LogLuvDecode24; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv24toXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv24toLuv48; break; case SGILOGDATAFMT_8BIT: sp->tfunc = Luv24toRGB; break; } } else { tif->tif_decoderow = LogLuvDecode32; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv32toXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv32toLuv48; break; case SGILOGDATAFMT_8BIT: sp->tfunc = Luv32toRGB; break; } } return (1); case PHOTOMETRIC_LOGL: if (!LogL16InitState(tif)) break; tif->tif_decoderow = LogL16Decode; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = L16toY; break; case SGILOGDATAFMT_8BIT: sp->tfunc = L16toGry; break; } return (1); default: TIFFErrorExt(tif->tif_clientdata, module, "Inappropriate photometric interpretation %d for SGILog compression; %s", td->td_photometric, "must be either LogLUV or LogL"); break; } return (0); } static int LogLuvSetupEncode(TIFF* tif) { static const char module[] = "LogLuvSetupEncode"; LogLuvState* sp = EncoderState(tif); TIFFDirectory* td = &tif->tif_dir; switch (td->td_photometric) { case PHOTOMETRIC_LOGLUV: if (!LogLuvInitState(tif)) break; if (td->td_compression == COMPRESSION_SGILOG24) { tif->tif_encoderow = LogLuvEncode24; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv24fromXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv24fromLuv48; break; case SGILOGDATAFMT_RAW: break; default: goto notsupported; } } else { tif->tif_encoderow = LogLuvEncode32; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv32fromXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv32fromLuv48; break; case SGILOGDATAFMT_RAW: break; default: goto notsupported; } } break; case PHOTOMETRIC_LOGL: if (!LogL16InitState(tif)) break; tif->tif_encoderow = LogL16Encode; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = L16fromY; break; case SGILOGDATAFMT_16BIT: break; default: goto notsupported; } break; default: TIFFErrorExt(tif->tif_clientdata, module, "Inappropriate photometric interpretation %d for SGILog compression; %s", td->td_photometric, "must be either LogLUV or LogL"); break; } return (1); notsupported: TIFFErrorExt(tif->tif_clientdata, module, "SGILog compression supported only for %s, or raw data", td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv"); return (0); } static void LogLuvClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* * For consistency, we always want to write out the same * bitspersample and sampleformat for our TIFF file, * regardless of the data format being used by the application. * Since this routine is called after tags have been set but * before they have been recorded in the file, we reset them here. */ td->td_samplesperpixel = (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3; td->td_bitspersample = 16; td->td_sampleformat = SAMPLEFORMAT_INT; } static void LogLuvCleanup(TIFF* tif) { LogLuvState* sp = (LogLuvState *)tif->tif_data; assert(sp != 0); tif->tif_tagmethods.vgetfield = sp->vgetparent; tif->tif_tagmethods.vsetfield = sp->vsetparent; if (sp->tbuf) _TIFFfree(sp->tbuf); _TIFFfree(sp); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } static int LogLuvVSetField(TIFF* tif, uint32 tag, va_list ap) { static const char module[] = "LogLuvVSetField"; LogLuvState* sp = DecoderState(tif); int bps, fmt; switch (tag) { case TIFFTAG_SGILOGDATAFMT: sp->user_datafmt = (int) va_arg(ap, int); /* * Tweak the TIFF header so that the rest of libtiff knows what * size of data will be passed between app and library, and * assume that the app knows what it is doing and is not * confused by these header manipulations... */ switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: bps = 32; fmt = SAMPLEFORMAT_IEEEFP; break; case SGILOGDATAFMT_16BIT: bps = 16; fmt = SAMPLEFORMAT_INT; break; case SGILOGDATAFMT_RAW: bps = 32; fmt = SAMPLEFORMAT_UINT; TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1); break; case SGILOGDATAFMT_8BIT: bps = 8; fmt = SAMPLEFORMAT_UINT; break; default: TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Unknown data format %d for LogLuv compression", sp->user_datafmt); return (0); } TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, fmt); /* * Must recalculate sizes should bits/sample change. */ tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t) -1; tif->tif_scanlinesize = TIFFScanlineSize(tif); return (1); case TIFFTAG_SGILOGENCODE: sp->encode_meth = (int) va_arg(ap, int); if (sp->encode_meth != SGILOGENCODE_NODITHER && sp->encode_meth != SGILOGENCODE_RANDITHER) { TIFFErrorExt(tif->tif_clientdata, module, "Unknown encoding %d for LogLuv compression", sp->encode_meth); return (0); } return (1); default: return (*sp->vsetparent)(tif, tag, ap); } } static int LogLuvVGetField(TIFF* tif, uint32 tag, va_list ap) { LogLuvState *sp = (LogLuvState *)tif->tif_data; switch (tag) { case TIFFTAG_SGILOGDATAFMT: *va_arg(ap, int*) = sp->user_datafmt; return (1); default: return (*sp->vgetparent)(tif, tag, ap); } } static const TIFFField LogLuvFields[] = { { TIFFTAG_SGILOGDATAFMT, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogDataFmt", NULL}, { TIFFTAG_SGILOGENCODE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "SGILogEncode", NULL} }; int TIFFInitSGILog(TIFF* tif, int scheme) { static const char module[] = "TIFFInitSGILog"; LogLuvState* sp; assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFields(tif, LogLuvFields, TIFFArrayCount(LogLuvFields))) { TIFFErrorExt(tif->tif_clientdata, module, "Merging SGILog codec-specific tags failed"); return 0; } /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LogLuvState)); if (tif->tif_data == NULL) goto bad; sp = (LogLuvState*) tif->tif_data; _TIFFmemset((void*)sp, 0, sizeof (*sp)); sp->user_datafmt = SGILOGDATAFMT_UNKNOWN; sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ? SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER; sp->tfunc = _logLuvNop; /* * Install codec methods. * NB: tif_decoderow & tif_encoderow are filled * in at setup time. */ tif->tif_fixuptags = LogLuvFixupTags; tif->tif_setupdecode = LogLuvSetupDecode; tif->tif_decodestrip = LogLuvDecodeStrip; tif->tif_decodetile = LogLuvDecodeTile; tif->tif_setupencode = LogLuvSetupEncode; tif->tif_encodestrip = LogLuvEncodeStrip; tif->tif_encodetile = LogLuvEncodeTile; tif->tif_close = LogLuvClose; tif->tif_cleanup = LogLuvCleanup; /* * Override parent get/set field methods. */ sp->vgetparent = tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield = LogLuvVGetField; /* hook for codec tags */ sp->vsetparent = tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield = LogLuvVSetField; /* hook for codec tags */ return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "%s: No space for LogLuv state block", tif->tif_name); return (0); } #endif /* LOGLUV_SUPPORT */ /* 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-125/c/bad_4856_1
crossvul-cpp_data_good_2706_0
/* * Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more * complete PPP support. */ /* \summary: Point to Point Protocol (PPP) printer */ /* * TODO: * o resolve XXX as much as possible * o MP support * o BAP support */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #ifdef __bsdi__ #include <net/slcompress.h> #include <net/if_ppp.h> #endif #include <stdlib.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ppp.h" #include "chdlc.h" #include "ethertype.h" #include "oui.h" /* * The following constatns are defined by IANA. Please refer to * http://www.isi.edu/in-notes/iana/assignments/ppp-numbers * for the up-to-date information. */ /* Protocol Codes defined in ppp.h */ static const struct tok ppptype2str[] = { { PPP_IP, "IP" }, { PPP_OSI, "OSI" }, { PPP_NS, "NS" }, { PPP_DECNET, "DECNET" }, { PPP_APPLE, "APPLE" }, { PPP_IPX, "IPX" }, { PPP_VJC, "VJC IP" }, { PPP_VJNC, "VJNC IP" }, { PPP_BRPDU, "BRPDU" }, { PPP_STII, "STII" }, { PPP_VINES, "VINES" }, { PPP_MPLS_UCAST, "MPLS" }, { PPP_MPLS_MCAST, "MPLS" }, { PPP_COMP, "Compressed"}, { PPP_ML, "MLPPP"}, { PPP_IPV6, "IP6"}, { PPP_HELLO, "HELLO" }, { PPP_LUXCOM, "LUXCOM" }, { PPP_SNS, "SNS" }, { PPP_IPCP, "IPCP" }, { PPP_OSICP, "OSICP" }, { PPP_NSCP, "NSCP" }, { PPP_DECNETCP, "DECNETCP" }, { PPP_APPLECP, "APPLECP" }, { PPP_IPXCP, "IPXCP" }, { PPP_STIICP, "STIICP" }, { PPP_VINESCP, "VINESCP" }, { PPP_IPV6CP, "IP6CP" }, { PPP_MPLSCP, "MPLSCP" }, { PPP_LCP, "LCP" }, { PPP_PAP, "PAP" }, { PPP_LQM, "LQM" }, { PPP_CHAP, "CHAP" }, { PPP_EAP, "EAP" }, { PPP_SPAP, "SPAP" }, { PPP_SPAP_OLD, "Old-SPAP" }, { PPP_BACP, "BACP" }, { PPP_BAP, "BAP" }, { PPP_MPCP, "MLPPP-CP" }, { PPP_CCP, "CCP" }, { 0, NULL } }; /* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */ #define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */ #define CPCODES_CONF_REQ 1 /* Configure-Request */ #define CPCODES_CONF_ACK 2 /* Configure-Ack */ #define CPCODES_CONF_NAK 3 /* Configure-Nak */ #define CPCODES_CONF_REJ 4 /* Configure-Reject */ #define CPCODES_TERM_REQ 5 /* Terminate-Request */ #define CPCODES_TERM_ACK 6 /* Terminate-Ack */ #define CPCODES_CODE_REJ 7 /* Code-Reject */ #define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */ #define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */ #define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */ #define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */ #define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */ #define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */ #define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */ #define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */ static const struct tok cpcodes[] = { {CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */ {CPCODES_CONF_REQ, "Conf-Request"}, {CPCODES_CONF_ACK, "Conf-Ack"}, {CPCODES_CONF_NAK, "Conf-Nack"}, {CPCODES_CONF_REJ, "Conf-Reject"}, {CPCODES_TERM_REQ, "Term-Request"}, {CPCODES_TERM_ACK, "Term-Ack"}, {CPCODES_CODE_REJ, "Code-Reject"}, {CPCODES_PROT_REJ, "Prot-Reject"}, {CPCODES_ECHO_REQ, "Echo-Request"}, {CPCODES_ECHO_RPL, "Echo-Reply"}, {CPCODES_DISC_REQ, "Disc-Req"}, {CPCODES_ID, "Ident"}, /* RFC1570 */ {CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */ {CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */ {CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */ {0, NULL} }; /* LCP Config Options */ #define LCPOPT_VEXT 0 #define LCPOPT_MRU 1 #define LCPOPT_ACCM 2 #define LCPOPT_AP 3 #define LCPOPT_QP 4 #define LCPOPT_MN 5 #define LCPOPT_DEP6 6 #define LCPOPT_PFC 7 #define LCPOPT_ACFC 8 #define LCPOPT_FCSALT 9 #define LCPOPT_SDP 10 #define LCPOPT_NUMMODE 11 #define LCPOPT_DEP12 12 #define LCPOPT_CBACK 13 #define LCPOPT_DEP14 14 #define LCPOPT_DEP15 15 #define LCPOPT_DEP16 16 #define LCPOPT_MLMRRU 17 #define LCPOPT_MLSSNHF 18 #define LCPOPT_MLED 19 #define LCPOPT_PROP 20 #define LCPOPT_DCEID 21 #define LCPOPT_MPP 22 #define LCPOPT_LD 23 #define LCPOPT_LCPAOPT 24 #define LCPOPT_COBS 25 #define LCPOPT_PE 26 #define LCPOPT_MLHF 27 #define LCPOPT_I18N 28 #define LCPOPT_SDLOS 29 #define LCPOPT_PPPMUX 30 #define LCPOPT_MIN LCPOPT_VEXT #define LCPOPT_MAX LCPOPT_PPPMUX static const char *lcpconfopts[] = { "Vend-Ext", /* (0) */ "MRU", /* (1) */ "ACCM", /* (2) */ "Auth-Prot", /* (3) */ "Qual-Prot", /* (4) */ "Magic-Num", /* (5) */ "deprecated(6)", /* used to be a Quality Protocol */ "PFC", /* (7) */ "ACFC", /* (8) */ "FCS-Alt", /* (9) */ "SDP", /* (10) */ "Num-Mode", /* (11) */ "deprecated(12)", /* used to be a Multi-Link-Procedure*/ "Call-Back", /* (13) */ "deprecated(14)", /* used to be a Connect-Time */ "deprecated(15)", /* used to be a Compund-Frames */ "deprecated(16)", /* used to be a Nominal-Data-Encap */ "MRRU", /* (17) */ "12-Bit seq #", /* (18) */ "End-Disc", /* (19) */ "Proprietary", /* (20) */ "DCE-Id", /* (21) */ "MP+", /* (22) */ "Link-Disc", /* (23) */ "LCP-Auth-Opt", /* (24) */ "COBS", /* (25) */ "Prefix-elision", /* (26) */ "Multilink-header-Form",/* (27) */ "I18N", /* (28) */ "SDL-over-SONET/SDH", /* (29) */ "PPP-Muxing", /* (30) */ }; /* ECP - to be supported */ /* CCP Config Options */ #define CCPOPT_OUI 0 /* RFC1962 */ #define CCPOPT_PRED1 1 /* RFC1962 */ #define CCPOPT_PRED2 2 /* RFC1962 */ #define CCPOPT_PJUMP 3 /* RFC1962 */ /* 4-15 unassigned */ #define CCPOPT_HPPPC 16 /* RFC1962 */ #define CCPOPT_STACLZS 17 /* RFC1974 */ #define CCPOPT_MPPC 18 /* RFC2118 */ #define CCPOPT_GFZA 19 /* RFC1962 */ #define CCPOPT_V42BIS 20 /* RFC1962 */ #define CCPOPT_BSDCOMP 21 /* RFC1977 */ /* 22 unassigned */ #define CCPOPT_LZSDCP 23 /* RFC1967 */ #define CCPOPT_MVRCA 24 /* RFC1975 */ #define CCPOPT_DEC 25 /* RFC1976 */ #define CCPOPT_DEFLATE 26 /* RFC1979 */ /* 27-254 unassigned */ #define CCPOPT_RESV 255 /* RFC1962 */ static const struct tok ccpconfopts_values[] = { { CCPOPT_OUI, "OUI" }, { CCPOPT_PRED1, "Pred-1" }, { CCPOPT_PRED2, "Pred-2" }, { CCPOPT_PJUMP, "Puddle" }, { CCPOPT_HPPPC, "HP-PPC" }, { CCPOPT_STACLZS, "Stac-LZS" }, { CCPOPT_MPPC, "MPPC" }, { CCPOPT_GFZA, "Gand-FZA" }, { CCPOPT_V42BIS, "V.42bis" }, { CCPOPT_BSDCOMP, "BSD-Comp" }, { CCPOPT_LZSDCP, "LZS-DCP" }, { CCPOPT_MVRCA, "MVRCA" }, { CCPOPT_DEC, "DEC" }, { CCPOPT_DEFLATE, "Deflate" }, { CCPOPT_RESV, "Reserved"}, {0, NULL} }; /* BACP Config Options */ #define BACPOPT_FPEER 1 /* RFC2125 */ static const struct tok bacconfopts_values[] = { { BACPOPT_FPEER, "Favored-Peer" }, {0, NULL} }; /* SDCP - to be supported */ /* IPCP Config Options */ #define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */ #define IPCPOPT_IPCOMP 2 /* RFC1332 */ #define IPCPOPT_ADDR 3 /* RFC1332 */ #define IPCPOPT_MOBILE4 4 /* RFC2290 */ #define IPCPOPT_PRIDNS 129 /* RFC1877 */ #define IPCPOPT_PRINBNS 130 /* RFC1877 */ #define IPCPOPT_SECDNS 131 /* RFC1877 */ #define IPCPOPT_SECNBNS 132 /* RFC1877 */ static const struct tok ipcpopt_values[] = { { IPCPOPT_2ADDR, "IP-Addrs" }, { IPCPOPT_IPCOMP, "IP-Comp" }, { IPCPOPT_ADDR, "IP-Addr" }, { IPCPOPT_MOBILE4, "Home-Addr" }, { IPCPOPT_PRIDNS, "Pri-DNS" }, { IPCPOPT_PRINBNS, "Pri-NBNS" }, { IPCPOPT_SECDNS, "Sec-DNS" }, { IPCPOPT_SECNBNS, "Sec-NBNS" }, { 0, NULL } }; #define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */ #define IPCPOPT_IPCOMP_MINLEN 14 static const struct tok ipcpopt_compproto_values[] = { { PPP_VJC, "VJ-Comp" }, { IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" }, { 0, NULL } }; static const struct tok ipcpopt_compproto_subopt_values[] = { { 1, "RTP-Compression" }, { 2, "Enhanced RTP-Compression" }, { 0, NULL } }; /* IP6CP Config Options */ #define IP6CP_IFID 1 static const struct tok ip6cpopt_values[] = { { IP6CP_IFID, "Interface-ID" }, { 0, NULL } }; /* ATCP - to be supported */ /* OSINLCP - to be supported */ /* BVCP - to be supported */ /* BCP - to be supported */ /* IPXCP - to be supported */ /* MPLSCP - to be supported */ /* Auth Algorithms */ /* 0-4 Reserved (RFC1994) */ #define AUTHALG_CHAPMD5 5 /* RFC1994 */ #define AUTHALG_MSCHAP1 128 /* RFC2433 */ #define AUTHALG_MSCHAP2 129 /* RFC2795 */ static const struct tok authalg_values[] = { { AUTHALG_CHAPMD5, "MD5" }, { AUTHALG_MSCHAP1, "MS-CHAPv1" }, { AUTHALG_MSCHAP2, "MS-CHAPv2" }, { 0, NULL } }; /* FCS Alternatives - to be supported */ /* Multilink Endpoint Discriminator (RFC1717) */ #define MEDCLASS_NULL 0 /* Null Class */ #define MEDCLASS_LOCAL 1 /* Locally Assigned */ #define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */ #define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */ #define MEDCLASS_MNB 4 /* PPP Magic Number Block */ #define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */ /* PPP LCP Callback */ #define CALLBACK_AUTH 0 /* Location determined by user auth */ #define CALLBACK_DSTR 1 /* Dialing string */ #define CALLBACK_LID 2 /* Location identifier */ #define CALLBACK_E164 3 /* E.164 number */ #define CALLBACK_X500 4 /* X.500 distinguished name */ #define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */ static const struct tok ppp_callback_values[] = { { CALLBACK_AUTH, "UserAuth" }, { CALLBACK_DSTR, "DialString" }, { CALLBACK_LID, "LocalID" }, { CALLBACK_E164, "E.164" }, { CALLBACK_X500, "X.500" }, { CALLBACK_CBCP, "CBCP" }, { 0, NULL } }; /* CHAP */ #define CHAP_CHAL 1 #define CHAP_RESP 2 #define CHAP_SUCC 3 #define CHAP_FAIL 4 static const struct tok chapcode_values[] = { { CHAP_CHAL, "Challenge" }, { CHAP_RESP, "Response" }, { CHAP_SUCC, "Success" }, { CHAP_FAIL, "Fail" }, { 0, NULL} }; /* PAP */ #define PAP_AREQ 1 #define PAP_AACK 2 #define PAP_ANAK 3 static const struct tok papcode_values[] = { { PAP_AREQ, "Auth-Req" }, { PAP_AACK, "Auth-ACK" }, { PAP_ANAK, "Auth-NACK" }, { 0, NULL } }; /* BAP */ #define BAP_CALLREQ 1 #define BAP_CALLRES 2 #define BAP_CBREQ 3 #define BAP_CBRES 4 #define BAP_LDQREQ 5 #define BAP_LDQRES 6 #define BAP_CSIND 7 #define BAP_CSRES 8 static int print_lcp_config_options(netdissect_options *, const u_char *p, int); static int print_ipcp_config_options(netdissect_options *, const u_char *p, int); static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int); static int print_ccp_config_options(netdissect_options *, const u_char *p, int); static int print_bacp_config_options(netdissect_options *, const u_char *p, int); static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length); /* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */ static void handle_ctrl_proto(netdissect_options *ndo, u_int proto, const u_char *pptr, int length) { const char *typestr; u_int code, len; int (*pfunc)(netdissect_options *, const u_char *, int); int x, j; const u_char *tptr; tptr=pptr; typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto); ND_PRINT((ndo, "%s, ", typestr)); if (length < 4) /* FIXME weak boundary checking */ goto trunc; ND_TCHECK2(*tptr, 2); code = *tptr++; ND_PRINT((ndo, "%s (0x%02x), id %u, length %u", tok2str(cpcodes, "Unknown Opcode",code), code, *tptr++, /* ID */ length + 2)); if (!ndo->ndo_vflag) return; if (length <= 4) return; /* there may be a NULL confreq etc. */ ND_TCHECK2(*tptr, 2); len = EXTRACT_16BITS(tptr); tptr += 2; ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr - 2, "\n\t", 6); switch (code) { case CPCODES_VEXT: if (length < 11) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); tptr += 4; ND_TCHECK2(*tptr, 3); ND_PRINT((ndo, " Vendor: %s (%u)", tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr))); /* XXX: need to decode Kind and Value(s)? */ break; case CPCODES_CONF_REQ: case CPCODES_CONF_ACK: case CPCODES_CONF_NAK: case CPCODES_CONF_REJ: x = len - 4; /* Code(1), Identifier(1) and Length(2) */ do { switch (proto) { case PPP_LCP: pfunc = print_lcp_config_options; break; case PPP_IPCP: pfunc = print_ipcp_config_options; break; case PPP_IPV6CP: pfunc = print_ip6cp_config_options; break; case PPP_CCP: pfunc = print_ccp_config_options; break; case PPP_BACP: pfunc = print_bacp_config_options; break; default: /* * No print routine for the options for * this protocol. */ pfunc = NULL; break; } if (pfunc == NULL) /* catch the above null pointer if unknown CP */ break; if ((j = (*pfunc)(ndo, tptr, len)) == 0) break; x -= j; tptr += j; } while (x > 0); break; case CPCODES_TERM_REQ: case CPCODES_TERM_ACK: /* XXX: need to decode Data? */ break; case CPCODES_CODE_REJ: /* XXX: need to decode Rejected-Packet? */ break; case CPCODES_PROT_REJ: if (length < 6) break; ND_TCHECK2(*tptr, 2); ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)", tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); /* XXX: need to decode Rejected-Information? - hexdump for now */ if (len > 6) { ND_PRINT((ndo, "\n\t Rejected Packet")); print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2); } break; case CPCODES_ECHO_REQ: case CPCODES_ECHO_RPL: case CPCODES_DISC_REQ: if (length < 8) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); /* XXX: need to decode Data? - hexdump for now */ if (len > 8) { ND_PRINT((ndo, "\n\t -----trailing data-----")); ND_TCHECK2(tptr[4], len - 8); print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8); } break; case CPCODES_ID: if (length < 8) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); /* RFC 1661 says this is intended to be human readable */ if (len > 8) { ND_PRINT((ndo, "\n\t Message\n\t ")); if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend)) goto trunc; } break; case CPCODES_TIME_REM: if (length < 12) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4))); /* XXX: need to decode Message? */ break; default: /* XXX this is dirty but we do not get the * original pointer passed to the begin * the PPP packet */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2); break; } return; trunc: ND_PRINT((ndo, "[|%s]", typestr)); } /* LCP config options */ static int print_lcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", lcpconfopts[opt], opt, len)); else ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt)); return 0; } if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len)); else { ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt)); return len; } switch (opt) { case LCPOPT_VEXT: if (len < 6) { ND_PRINT((ndo, " (length bogus, should be >= 6)")); return len; } ND_TCHECK_24BITS(p + 2); ND_PRINT((ndo, ": Vendor: %s (%u)", tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)), EXTRACT_24BITS(p + 2))); #if 0 ND_TCHECK(p[5]); ND_PRINT((ndo, ", kind: 0x%02x", p[5])); ND_PRINT((ndo, ", Value: 0x")); for (i = 0; i < len - 6; i++) { ND_TCHECK(p[6 + i]); ND_PRINT((ndo, "%02x", p[6 + i])); } #endif break; case LCPOPT_MRU: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return len; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2))); break; case LCPOPT_ACCM: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2))); break; case LCPOPT_AP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2)))); switch (EXTRACT_16BITS(p+2)) { case PPP_CHAP: ND_TCHECK(p[4]); ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4]))); break; case PPP_PAP: /* fall through */ case PPP_EAP: case PPP_SPAP: case PPP_SPAP_OLD: break; default: print_unknown_data(ndo, p, "\n\t", len); } break; case LCPOPT_QP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK_16BITS(p+2); if (EXTRACT_16BITS(p+2) == PPP_LQM) ND_PRINT((ndo, ": LQR")); else ND_PRINT((ndo, ": unknown")); break; case LCPOPT_MN: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2))); break; case LCPOPT_PFC: break; case LCPOPT_ACFC: break; case LCPOPT_LD: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return 0; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2))); break; case LCPOPT_CBACK: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return 0; } ND_PRINT((ndo, ": ")); ND_TCHECK(p[2]); ND_PRINT((ndo, ": Callback Operation %s (%u)", tok2str(ppp_callback_values, "Unknown", p[2]), p[2])); break; case LCPOPT_MLMRRU: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return 0; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2))); break; case LCPOPT_MLED: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return 0; } ND_TCHECK(p[2]); switch (p[2]) { /* class */ case MEDCLASS_NULL: ND_PRINT((ndo, ": Null")); break; case MEDCLASS_LOCAL: ND_PRINT((ndo, ": Local")); /* XXX */ break; case MEDCLASS_IPV4: if (len != 7) { ND_PRINT((ndo, " (length bogus, should be = 7)")); return 0; } ND_TCHECK2(*(p + 3), 4); ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3))); break; case MEDCLASS_MAC: if (len != 9) { ND_PRINT((ndo, " (length bogus, should be = 9)")); return 0; } ND_TCHECK2(*(p + 3), 6); ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3))); break; case MEDCLASS_MNB: ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */ break; case MEDCLASS_PSNDN: ND_PRINT((ndo, ": PSNDN")); /* XXX */ break; default: ND_PRINT((ndo, ": Unknown class %u", p[2])); break; } break; /* XXX: to be supported */ #if 0 case LCPOPT_DEP6: case LCPOPT_FCSALT: case LCPOPT_SDP: case LCPOPT_NUMMODE: case LCPOPT_DEP12: case LCPOPT_DEP14: case LCPOPT_DEP15: case LCPOPT_DEP16: case LCPOPT_MLSSNHF: case LCPOPT_PROP: case LCPOPT_DCEID: case LCPOPT_MPP: case LCPOPT_LCPAOPT: case LCPOPT_COBS: case LCPOPT_PE: case LCPOPT_MLHF: case LCPOPT_I18N: case LCPOPT_SDLOS: case LCPOPT_PPPMUX: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|lcp]")); return 0; } /* ML-PPP*/ static const struct tok ppp_ml_flag_values[] = { { 0x80, "begin" }, { 0x40, "end" }, { 0, NULL } }; static void handle_mlppp(netdissect_options *ndo, const u_char *p, int length) { if (!ndo->ndo_eflag) ND_PRINT((ndo, "MLPPP, ")); ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u", (EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */ bittok2str(ppp_ml_flag_values, "none", *p & 0xc0), length)); } /* CHAP */ static void handle_chap(netdissect_options *ndo, const u_char *p, int length) { u_int code, len; int val_size, name_size, msg_size; const u_char *p0; int i; p0 = p; if (length < 1) { ND_PRINT((ndo, "[|chap]")); return; } else if (length < 4) { ND_TCHECK(*p); ND_PRINT((ndo, "[|chap 0x%02x]", *p)); return; } ND_TCHECK(*p); code = *p; ND_PRINT((ndo, "CHAP, %s (0x%02x)", tok2str(chapcode_values,"unknown",code), code)); p++; ND_TCHECK(*p); ND_PRINT((ndo, ", id %u", *p)); /* ID */ p++; ND_TCHECK2(*p, 2); len = EXTRACT_16BITS(p); p += 2; /* * Note that this is a generic CHAP decoding routine. Since we * don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1, * MS-CHAPv2) is used at this point, we can't decode packet * specifically to each algorithms. Instead, we simply decode * the GCD (Gratest Common Denominator) for all algorithms. */ switch (code) { case CHAP_CHAL: case CHAP_RESP: if (length - (p - p0) < 1) return; ND_TCHECK(*p); val_size = *p; /* value size */ p++; if (length - (p - p0) < val_size) return; ND_PRINT((ndo, ", Value ")); for (i = 0; i < val_size; i++) { ND_TCHECK(*p); ND_PRINT((ndo, "%02x", *p++)); } name_size = len - (p - p0); ND_PRINT((ndo, ", Name ")); for (i = 0; i < name_size; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; case CHAP_SUCC: case CHAP_FAIL: msg_size = len - (p - p0); ND_PRINT((ndo, ", Msg ")); for (i = 0; i< msg_size; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; } return; trunc: ND_PRINT((ndo, "[|chap]")); } /* PAP (see RFC 1334) */ static void handle_pap(netdissect_options *ndo, const u_char *p, int length) { u_int code, len; int peerid_len, passwd_len, msg_len; const u_char *p0; int i; p0 = p; if (length < 1) { ND_PRINT((ndo, "[|pap]")); return; } else if (length < 4) { ND_TCHECK(*p); ND_PRINT((ndo, "[|pap 0x%02x]", *p)); return; } ND_TCHECK(*p); code = *p; ND_PRINT((ndo, "PAP, %s (0x%02x)", tok2str(papcode_values, "unknown", code), code)); p++; ND_TCHECK(*p); ND_PRINT((ndo, ", id %u", *p)); /* ID */ p++; ND_TCHECK2(*p, 2); len = EXTRACT_16BITS(p); p += 2; if ((int)len > length) { ND_PRINT((ndo, ", length %u > packet size", len)); return; } length = len; if (length < (p - p0)) { ND_PRINT((ndo, ", length %u < PAP header length", length)); return; } switch (code) { case PAP_AREQ: /* A valid Authenticate-Request is 6 or more octets long. */ if (len < 6) goto trunc; if (length - (p - p0) < 1) return; ND_TCHECK(*p); peerid_len = *p; /* Peer-ID Length */ p++; if (length - (p - p0) < peerid_len) return; ND_PRINT((ndo, ", Peer ")); for (i = 0; i < peerid_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } if (length - (p - p0) < 1) return; ND_TCHECK(*p); passwd_len = *p; /* Password Length */ p++; if (length - (p - p0) < passwd_len) return; ND_PRINT((ndo, ", Name ")); for (i = 0; i < passwd_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; case PAP_AACK: case PAP_ANAK: /* Although some implementations ignore truncation at * this point and at least one generates a truncated * packet, RFC 1334 section 2.2.2 clearly states that * both AACK and ANAK are at least 5 bytes long. */ if (len < 5) goto trunc; if (length - (p - p0) < 1) return; ND_TCHECK(*p); msg_len = *p; /* Msg-Length */ p++; if (length - (p - p0) < msg_len) return; ND_PRINT((ndo, ", Msg ")); for (i = 0; i< msg_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; } return; trunc: ND_PRINT((ndo, "[|pap]")); } /* BAP */ static void handle_bap(netdissect_options *ndo _U_, const u_char *p _U_, int length _U_) { /* XXX: to be supported!! */ } /* IPCP config options */ static int print_ipcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ipcpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ipcpopt_values,"unknown",opt), opt, len)); switch (opt) { case IPCPOPT_2ADDR: /* deprecated */ if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 6), 4); ND_PRINT((ndo, ": src %s, dst %s", ipaddr_string(ndo, p + 2), ipaddr_string(ndo, p + 6))); break; case IPCPOPT_IPCOMP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK_16BITS(p+2); compproto = EXTRACT_16BITS(p+2); ND_PRINT((ndo, ": %s (0x%02x):", tok2str(ipcpopt_compproto_values, "Unknown", compproto), compproto)); switch (compproto) { case PPP_VJC: /* XXX: VJ-Comp parameters should be decoded */ break; case IPCPOPT_IPCOMP_HDRCOMP: if (len < IPCPOPT_IPCOMP_MINLEN) { ND_PRINT((ndo, " (length bogus, should be >= %u)", IPCPOPT_IPCOMP_MINLEN)); return 0; } ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN); ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \ ", maxPeriod %u, maxTime %u, maxHdr %u", EXTRACT_16BITS(p+4), EXTRACT_16BITS(p+6), EXTRACT_16BITS(p+8), EXTRACT_16BITS(p+10), EXTRACT_16BITS(p+12))); /* suboptions present ? */ if (len > IPCPOPT_IPCOMP_MINLEN) { ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN; p += IPCPOPT_IPCOMP_MINLEN; ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen)); while (ipcomp_subopttotallen >= 2) { ND_TCHECK2(*p, 2); ipcomp_subopt = *p; ipcomp_suboptlen = *(p+1); /* sanity check */ if (ipcomp_subopt == 0 || ipcomp_suboptlen == 0 ) break; /* XXX: just display the suboptions for now */ ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u", tok2str(ipcpopt_compproto_subopt_values, "Unknown", ipcomp_subopt), ipcomp_subopt, ipcomp_suboptlen)); ipcomp_subopttotallen -= ipcomp_suboptlen; p += ipcomp_suboptlen; } } break; default: break; } break; case IPCPOPT_ADDR: /* those options share the same format - fall through */ case IPCPOPT_MOBILE4: case IPCPOPT_PRIDNS: case IPCPOPT_PRINBNS: case IPCPOPT_SECDNS: case IPCPOPT_SECNBNS: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ipcp]")); return 0; } /* IP6CP config options */ static int print_ip6cp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ip6cpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ip6cpopt_values,"unknown",opt), opt, len)); switch (opt) { case IP6CP_IFID: if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 2), 8); ND_PRINT((ndo, ": %04x:%04x:%04x:%04x", EXTRACT_16BITS(p + 2), EXTRACT_16BITS(p + 4), EXTRACT_16BITS(p + 6), EXTRACT_16BITS(p + 8))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ip6cp]")); return 0; } /* CCP config options */ static int print_ccp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case CCPOPT_BSDCOMP: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return len; } ND_TCHECK(p[2]); ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u", p[2] >> 5, p[2] & 0x1f)); break; case CCPOPT_MVRCA: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK(p[3]); ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u", (p[2] & 0xc0) >> 6, (p[2] & 0x20) ? "Enabled" : "Disabled", p[2] & 0x1f, p[3])); break; case CCPOPT_DEFLATE: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK(p[3]); ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u", (p[2] & 0xf0) >> 4, ((p[2] & 0x0f) == 8) ? "zlib" : "unknown", p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); break; /* XXX: to be supported */ #if 0 case CCPOPT_OUI: case CCPOPT_PRED1: case CCPOPT_PRED2: case CCPOPT_PJUMP: case CCPOPT_HPPPC: case CCPOPT_STACLZS: case CCPOPT_MPPC: case CCPOPT_GFZA: case CCPOPT_V42BIS: case CCPOPT_LZSDCP: case CCPOPT_DEC: case CCPOPT_RESV: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ccp]")); return 0; } /* BACP config options */ static int print_bacp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case BACPOPT_FPEER: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|bacp]")); return 0; } static void ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *t, c; const u_char *s; int i, proto; const void *se; if (length <= 0) return; b = (u_char *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { c = *s++; if (c == 0x7d) { if (i <= 1 || !ND_TTEST(*s)) break; i--; c = *s++ ^ 0x20; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); } /* PPP */ static void handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } } /* Standard PPP printer */ u_int ppp_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto,ppp_header; u_int olen = length; /* _o_riginal length */ u_int hdr_len = 0; /* * Here, we assume that p points to the Address and Control * field (if they present). */ if (length < 2) goto trunc; ND_TCHECK2(*p, 2); ppp_header = EXTRACT_16BITS(p); switch(ppp_header) { case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL): if (ndo->ndo_eflag) ND_PRINT((ndo, "In ")); p += 2; length -= 2; hdr_len += 2; break; case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL): if (ndo->ndo_eflag) ND_PRINT((ndo, "Out ")); p += 2; length -= 2; hdr_len += 2; break; case (PPP_ADDRESS << 8 | PPP_CONTROL): p += 2; /* ACFC not used */ length -= 2; hdr_len += 2; break; default: break; } if (length < 2) goto trunc; ND_TCHECK(*p); if (*p % 2) { proto = *p; /* PFC is used */ p++; length--; hdr_len++; } else { ND_TCHECK2(*p, 2); proto = EXTRACT_16BITS(p); p += 2; length -= 2; hdr_len += 2; } if (ndo->ndo_eflag) ND_PRINT((ndo, "%s (0x%04x), length %u: ", tok2str(ppptype2str, "unknown", proto), proto, olen)); handle_ppp(ndo, proto, p, length); return (hdr_len); trunc: ND_PRINT((ndo, "[|ppp]")); return (0); } /* PPP I/F printer */ u_int ppp_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; if (caplen < PPP_HDRLEN) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } #if 0 /* * XXX: seems to assume that there are 2 octets prepended to an * actual PPP frame. The 1st octet looks like Input/Output flag * while 2nd octet is unknown, at least to me * (mshindo@mshindo.net). * * That was what the original tcpdump code did. * * FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound * packets and 0 for inbound packets - but only if the * protocol field has the 0x8000 bit set (i.e., it's a network * control protocol); it does so before running the packet through * "bpf_filter" to see if it should be discarded, and to see * if we should update the time we sent the most recent packet... * * ...but it puts the original address field back after doing * so. * * NetBSD's "if_ppp.c" doesn't set the first octet in that fashion. * * I don't know if any PPP implementation handed up to a BPF * device packets with the first octet being 1 for outbound and * 0 for inbound packets, so I (guy@alum.mit.edu) don't know * whether that ever needs to be checked or not. * * Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP, * and its tcpdump appears to assume that the frame always * begins with an address field and a control field, and that * the address field might be 0x0f or 0x8f, for Cisco * point-to-point with HDLC framing as per section 4.3.1 of RFC * 1547, as well as 0xff, for PPP in HDLC-like framing as per * RFC 1662. * * (Is the Cisco framing in question what DLT_C_HDLC, in * BSD/OS, is?) */ if (ndo->ndo_eflag) ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1])); #endif ppp_print(ndo, p, length); return (0); } /* * PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like * framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547, * is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL, * discard them *if* those are the first two octets, and parse the remaining * packet as a PPP packet, as "ppp_print()" does). * * This handles, for example, DLT_PPP_SERIAL in NetBSD. */ u_int ppp_hdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; u_int proto; u_int hdrlen = 0; if (caplen < 2) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } switch (p[0]) { case PPP_ADDRESS: if (caplen < 4) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length)); p += 2; length -= 2; hdrlen += 2; proto = EXTRACT_16BITS(p); p += 2; length -= 2; hdrlen += 2; ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); handle_ppp(ndo, proto, p, length); break; case CHDLC_UNICAST: case CHDLC_BCAST: return (chdlc_if_print(ndo, h, p)); default: if (caplen < 4) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length)); p += 2; hdrlen += 2; /* * XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats * the next two octets as an Ethernet type; does that * ever happen? */ ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1])); break; } return (hdrlen); } #define PPP_BSDI_HDRLEN 24 /* BSD/OS specific PPP printer */ u_int ppp_bsdos_if_print(netdissect_options *ndo _U_, const struct pcap_pkthdr *h _U_, register const u_char *p _U_) { register int hdrlength; #ifdef __bsdi__ register u_int length = h->len; register u_int caplen = h->caplen; uint16_t ptype; const u_char *q; int i; if (caplen < PPP_BSDI_HDRLEN) { ND_PRINT((ndo, "[|ppp]")); return (caplen) } hdrlength = 0; #if 0 if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) { if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x ", p[0], p[1])); p += 2; hdrlength = 2; } if (ndo->ndo_eflag) ND_PRINT((ndo, "%d ", length)); /* Retrieve the protocol type */ if (*p & 01) { /* Compressed protocol field */ ptype = *p; if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x ", ptype)); p++; hdrlength += 1; } else { /* Un-compressed protocol field */ ptype = EXTRACT_16BITS(p); if (ndo->ndo_eflag) ND_PRINT((ndo, "%04x ", ptype)); p += 2; hdrlength += 2; } #else ptype = 0; /*XXX*/ if (ndo->ndo_eflag) ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I')); if (p[SLC_LLHL]) { /* link level header */ struct ppp_header *ph; q = p + SLC_BPFHDRLEN; ph = (struct ppp_header *)q; if (ph->phdr_addr == PPP_ADDRESS && ph->phdr_ctl == PPP_CONTROL) { if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x ", q[0], q[1])); ptype = EXTRACT_16BITS(&ph->phdr_type); if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) { ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "proto-#%d", ptype))); } } else { if (ndo->ndo_eflag) { ND_PRINT((ndo, "LLH=[")); for (i = 0; i < p[SLC_LLHL]; i++) ND_PRINT((ndo, "%02x", q[i])); ND_PRINT((ndo, "] ")); } } } if (ndo->ndo_eflag) ND_PRINT((ndo, "%d ", length)); if (p[SLC_CHL]) { q = p + SLC_BPFHDRLEN + p[SLC_LLHL]; switch (ptype) { case PPP_VJC: ptype = vjc_print(ndo, q, ptype); hdrlength = PPP_BSDI_HDRLEN; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(ndo, p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; } goto printx; case PPP_VJNC: ptype = vjc_print(ndo, q, ptype); hdrlength = PPP_BSDI_HDRLEN; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(ndo, p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; } goto printx; default: if (ndo->ndo_eflag) { ND_PRINT((ndo, "CH=[")); for (i = 0; i < p[SLC_LLHL]; i++) ND_PRINT((ndo, "%02x", q[i])); ND_PRINT((ndo, "] ")); } break; } } hdrlength = PPP_BSDI_HDRLEN; #endif length -= hdrlength; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype))); } printx: #else /* __bsdi */ hdrlength = 0; #endif /* __bsdi__ */ return (hdrlength); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2706_0
crossvul-cpp_data_good_267_0
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_TCHECK_32BITS(cp); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*k); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_id *idp; struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; idp = (const struct ikev2_id *)ext; ND_TCHECK(*idp); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK2(*ext, sizeof(a)); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_267_0
crossvul-cpp_data_good_2644_11
/* * Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more * complete PPP support. */ /* \summary: Point to Point Protocol (PPP) printer */ /* * TODO: * o resolve XXX as much as possible * o MP support * o BAP support */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #ifdef __bsdi__ #include <net/slcompress.h> #include <net/if_ppp.h> #endif #include <stdlib.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ppp.h" #include "chdlc.h" #include "ethertype.h" #include "oui.h" /* * The following constatns are defined by IANA. Please refer to * http://www.isi.edu/in-notes/iana/assignments/ppp-numbers * for the up-to-date information. */ /* Protocol Codes defined in ppp.h */ static const struct tok ppptype2str[] = { { PPP_IP, "IP" }, { PPP_OSI, "OSI" }, { PPP_NS, "NS" }, { PPP_DECNET, "DECNET" }, { PPP_APPLE, "APPLE" }, { PPP_IPX, "IPX" }, { PPP_VJC, "VJC IP" }, { PPP_VJNC, "VJNC IP" }, { PPP_BRPDU, "BRPDU" }, { PPP_STII, "STII" }, { PPP_VINES, "VINES" }, { PPP_MPLS_UCAST, "MPLS" }, { PPP_MPLS_MCAST, "MPLS" }, { PPP_COMP, "Compressed"}, { PPP_ML, "MLPPP"}, { PPP_IPV6, "IP6"}, { PPP_HELLO, "HELLO" }, { PPP_LUXCOM, "LUXCOM" }, { PPP_SNS, "SNS" }, { PPP_IPCP, "IPCP" }, { PPP_OSICP, "OSICP" }, { PPP_NSCP, "NSCP" }, { PPP_DECNETCP, "DECNETCP" }, { PPP_APPLECP, "APPLECP" }, { PPP_IPXCP, "IPXCP" }, { PPP_STIICP, "STIICP" }, { PPP_VINESCP, "VINESCP" }, { PPP_IPV6CP, "IP6CP" }, { PPP_MPLSCP, "MPLSCP" }, { PPP_LCP, "LCP" }, { PPP_PAP, "PAP" }, { PPP_LQM, "LQM" }, { PPP_CHAP, "CHAP" }, { PPP_EAP, "EAP" }, { PPP_SPAP, "SPAP" }, { PPP_SPAP_OLD, "Old-SPAP" }, { PPP_BACP, "BACP" }, { PPP_BAP, "BAP" }, { PPP_MPCP, "MLPPP-CP" }, { PPP_CCP, "CCP" }, { 0, NULL } }; /* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */ #define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */ #define CPCODES_CONF_REQ 1 /* Configure-Request */ #define CPCODES_CONF_ACK 2 /* Configure-Ack */ #define CPCODES_CONF_NAK 3 /* Configure-Nak */ #define CPCODES_CONF_REJ 4 /* Configure-Reject */ #define CPCODES_TERM_REQ 5 /* Terminate-Request */ #define CPCODES_TERM_ACK 6 /* Terminate-Ack */ #define CPCODES_CODE_REJ 7 /* Code-Reject */ #define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */ #define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */ #define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */ #define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */ #define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */ #define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */ #define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */ #define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */ static const struct tok cpcodes[] = { {CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */ {CPCODES_CONF_REQ, "Conf-Request"}, {CPCODES_CONF_ACK, "Conf-Ack"}, {CPCODES_CONF_NAK, "Conf-Nack"}, {CPCODES_CONF_REJ, "Conf-Reject"}, {CPCODES_TERM_REQ, "Term-Request"}, {CPCODES_TERM_ACK, "Term-Ack"}, {CPCODES_CODE_REJ, "Code-Reject"}, {CPCODES_PROT_REJ, "Prot-Reject"}, {CPCODES_ECHO_REQ, "Echo-Request"}, {CPCODES_ECHO_RPL, "Echo-Reply"}, {CPCODES_DISC_REQ, "Disc-Req"}, {CPCODES_ID, "Ident"}, /* RFC1570 */ {CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */ {CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */ {CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */ {0, NULL} }; /* LCP Config Options */ #define LCPOPT_VEXT 0 #define LCPOPT_MRU 1 #define LCPOPT_ACCM 2 #define LCPOPT_AP 3 #define LCPOPT_QP 4 #define LCPOPT_MN 5 #define LCPOPT_DEP6 6 #define LCPOPT_PFC 7 #define LCPOPT_ACFC 8 #define LCPOPT_FCSALT 9 #define LCPOPT_SDP 10 #define LCPOPT_NUMMODE 11 #define LCPOPT_DEP12 12 #define LCPOPT_CBACK 13 #define LCPOPT_DEP14 14 #define LCPOPT_DEP15 15 #define LCPOPT_DEP16 16 #define LCPOPT_MLMRRU 17 #define LCPOPT_MLSSNHF 18 #define LCPOPT_MLED 19 #define LCPOPT_PROP 20 #define LCPOPT_DCEID 21 #define LCPOPT_MPP 22 #define LCPOPT_LD 23 #define LCPOPT_LCPAOPT 24 #define LCPOPT_COBS 25 #define LCPOPT_PE 26 #define LCPOPT_MLHF 27 #define LCPOPT_I18N 28 #define LCPOPT_SDLOS 29 #define LCPOPT_PPPMUX 30 #define LCPOPT_MIN LCPOPT_VEXT #define LCPOPT_MAX LCPOPT_PPPMUX static const char *lcpconfopts[] = { "Vend-Ext", /* (0) */ "MRU", /* (1) */ "ACCM", /* (2) */ "Auth-Prot", /* (3) */ "Qual-Prot", /* (4) */ "Magic-Num", /* (5) */ "deprecated(6)", /* used to be a Quality Protocol */ "PFC", /* (7) */ "ACFC", /* (8) */ "FCS-Alt", /* (9) */ "SDP", /* (10) */ "Num-Mode", /* (11) */ "deprecated(12)", /* used to be a Multi-Link-Procedure*/ "Call-Back", /* (13) */ "deprecated(14)", /* used to be a Connect-Time */ "deprecated(15)", /* used to be a Compund-Frames */ "deprecated(16)", /* used to be a Nominal-Data-Encap */ "MRRU", /* (17) */ "12-Bit seq #", /* (18) */ "End-Disc", /* (19) */ "Proprietary", /* (20) */ "DCE-Id", /* (21) */ "MP+", /* (22) */ "Link-Disc", /* (23) */ "LCP-Auth-Opt", /* (24) */ "COBS", /* (25) */ "Prefix-elision", /* (26) */ "Multilink-header-Form",/* (27) */ "I18N", /* (28) */ "SDL-over-SONET/SDH", /* (29) */ "PPP-Muxing", /* (30) */ }; /* ECP - to be supported */ /* CCP Config Options */ #define CCPOPT_OUI 0 /* RFC1962 */ #define CCPOPT_PRED1 1 /* RFC1962 */ #define CCPOPT_PRED2 2 /* RFC1962 */ #define CCPOPT_PJUMP 3 /* RFC1962 */ /* 4-15 unassigned */ #define CCPOPT_HPPPC 16 /* RFC1962 */ #define CCPOPT_STACLZS 17 /* RFC1974 */ #define CCPOPT_MPPC 18 /* RFC2118 */ #define CCPOPT_GFZA 19 /* RFC1962 */ #define CCPOPT_V42BIS 20 /* RFC1962 */ #define CCPOPT_BSDCOMP 21 /* RFC1977 */ /* 22 unassigned */ #define CCPOPT_LZSDCP 23 /* RFC1967 */ #define CCPOPT_MVRCA 24 /* RFC1975 */ #define CCPOPT_DEC 25 /* RFC1976 */ #define CCPOPT_DEFLATE 26 /* RFC1979 */ /* 27-254 unassigned */ #define CCPOPT_RESV 255 /* RFC1962 */ static const struct tok ccpconfopts_values[] = { { CCPOPT_OUI, "OUI" }, { CCPOPT_PRED1, "Pred-1" }, { CCPOPT_PRED2, "Pred-2" }, { CCPOPT_PJUMP, "Puddle" }, { CCPOPT_HPPPC, "HP-PPC" }, { CCPOPT_STACLZS, "Stac-LZS" }, { CCPOPT_MPPC, "MPPC" }, { CCPOPT_GFZA, "Gand-FZA" }, { CCPOPT_V42BIS, "V.42bis" }, { CCPOPT_BSDCOMP, "BSD-Comp" }, { CCPOPT_LZSDCP, "LZS-DCP" }, { CCPOPT_MVRCA, "MVRCA" }, { CCPOPT_DEC, "DEC" }, { CCPOPT_DEFLATE, "Deflate" }, { CCPOPT_RESV, "Reserved"}, {0, NULL} }; /* BACP Config Options */ #define BACPOPT_FPEER 1 /* RFC2125 */ static const struct tok bacconfopts_values[] = { { BACPOPT_FPEER, "Favored-Peer" }, {0, NULL} }; /* SDCP - to be supported */ /* IPCP Config Options */ #define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */ #define IPCPOPT_IPCOMP 2 /* RFC1332 */ #define IPCPOPT_ADDR 3 /* RFC1332 */ #define IPCPOPT_MOBILE4 4 /* RFC2290 */ #define IPCPOPT_PRIDNS 129 /* RFC1877 */ #define IPCPOPT_PRINBNS 130 /* RFC1877 */ #define IPCPOPT_SECDNS 131 /* RFC1877 */ #define IPCPOPT_SECNBNS 132 /* RFC1877 */ static const struct tok ipcpopt_values[] = { { IPCPOPT_2ADDR, "IP-Addrs" }, { IPCPOPT_IPCOMP, "IP-Comp" }, { IPCPOPT_ADDR, "IP-Addr" }, { IPCPOPT_MOBILE4, "Home-Addr" }, { IPCPOPT_PRIDNS, "Pri-DNS" }, { IPCPOPT_PRINBNS, "Pri-NBNS" }, { IPCPOPT_SECDNS, "Sec-DNS" }, { IPCPOPT_SECNBNS, "Sec-NBNS" }, { 0, NULL } }; #define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */ #define IPCPOPT_IPCOMP_MINLEN 14 static const struct tok ipcpopt_compproto_values[] = { { PPP_VJC, "VJ-Comp" }, { IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" }, { 0, NULL } }; static const struct tok ipcpopt_compproto_subopt_values[] = { { 1, "RTP-Compression" }, { 2, "Enhanced RTP-Compression" }, { 0, NULL } }; /* IP6CP Config Options */ #define IP6CP_IFID 1 static const struct tok ip6cpopt_values[] = { { IP6CP_IFID, "Interface-ID" }, { 0, NULL } }; /* ATCP - to be supported */ /* OSINLCP - to be supported */ /* BVCP - to be supported */ /* BCP - to be supported */ /* IPXCP - to be supported */ /* MPLSCP - to be supported */ /* Auth Algorithms */ /* 0-4 Reserved (RFC1994) */ #define AUTHALG_CHAPMD5 5 /* RFC1994 */ #define AUTHALG_MSCHAP1 128 /* RFC2433 */ #define AUTHALG_MSCHAP2 129 /* RFC2795 */ static const struct tok authalg_values[] = { { AUTHALG_CHAPMD5, "MD5" }, { AUTHALG_MSCHAP1, "MS-CHAPv1" }, { AUTHALG_MSCHAP2, "MS-CHAPv2" }, { 0, NULL } }; /* FCS Alternatives - to be supported */ /* Multilink Endpoint Discriminator (RFC1717) */ #define MEDCLASS_NULL 0 /* Null Class */ #define MEDCLASS_LOCAL 1 /* Locally Assigned */ #define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */ #define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */ #define MEDCLASS_MNB 4 /* PPP Magic Number Block */ #define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */ /* PPP LCP Callback */ #define CALLBACK_AUTH 0 /* Location determined by user auth */ #define CALLBACK_DSTR 1 /* Dialing string */ #define CALLBACK_LID 2 /* Location identifier */ #define CALLBACK_E164 3 /* E.164 number */ #define CALLBACK_X500 4 /* X.500 distinguished name */ #define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */ static const struct tok ppp_callback_values[] = { { CALLBACK_AUTH, "UserAuth" }, { CALLBACK_DSTR, "DialString" }, { CALLBACK_LID, "LocalID" }, { CALLBACK_E164, "E.164" }, { CALLBACK_X500, "X.500" }, { CALLBACK_CBCP, "CBCP" }, { 0, NULL } }; /* CHAP */ #define CHAP_CHAL 1 #define CHAP_RESP 2 #define CHAP_SUCC 3 #define CHAP_FAIL 4 static const struct tok chapcode_values[] = { { CHAP_CHAL, "Challenge" }, { CHAP_RESP, "Response" }, { CHAP_SUCC, "Success" }, { CHAP_FAIL, "Fail" }, { 0, NULL} }; /* PAP */ #define PAP_AREQ 1 #define PAP_AACK 2 #define PAP_ANAK 3 static const struct tok papcode_values[] = { { PAP_AREQ, "Auth-Req" }, { PAP_AACK, "Auth-ACK" }, { PAP_ANAK, "Auth-NACK" }, { 0, NULL } }; /* BAP */ #define BAP_CALLREQ 1 #define BAP_CALLRES 2 #define BAP_CBREQ 3 #define BAP_CBRES 4 #define BAP_LDQREQ 5 #define BAP_LDQRES 6 #define BAP_CSIND 7 #define BAP_CSRES 8 static int print_lcp_config_options(netdissect_options *, const u_char *p, int); static int print_ipcp_config_options(netdissect_options *, const u_char *p, int); static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int); static int print_ccp_config_options(netdissect_options *, const u_char *p, int); static int print_bacp_config_options(netdissect_options *, const u_char *p, int); static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length); /* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */ static void handle_ctrl_proto(netdissect_options *ndo, u_int proto, const u_char *pptr, int length) { const char *typestr; u_int code, len; int (*pfunc)(netdissect_options *, const u_char *, int); int x, j; const u_char *tptr; tptr=pptr; typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto); ND_PRINT((ndo, "%s, ", typestr)); if (length < 4) /* FIXME weak boundary checking */ goto trunc; ND_TCHECK2(*tptr, 2); code = *tptr++; ND_PRINT((ndo, "%s (0x%02x), id %u, length %u", tok2str(cpcodes, "Unknown Opcode",code), code, *tptr++, /* ID */ length + 2)); if (!ndo->ndo_vflag) return; if (length <= 4) return; /* there may be a NULL confreq etc. */ ND_TCHECK2(*tptr, 2); len = EXTRACT_16BITS(tptr); tptr += 2; ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr - 2, "\n\t", 6); switch (code) { case CPCODES_VEXT: if (length < 11) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); tptr += 4; ND_TCHECK2(*tptr, 3); ND_PRINT((ndo, " Vendor: %s (%u)", tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr))); /* XXX: need to decode Kind and Value(s)? */ break; case CPCODES_CONF_REQ: case CPCODES_CONF_ACK: case CPCODES_CONF_NAK: case CPCODES_CONF_REJ: x = len - 4; /* Code(1), Identifier(1) and Length(2) */ do { switch (proto) { case PPP_LCP: pfunc = print_lcp_config_options; break; case PPP_IPCP: pfunc = print_ipcp_config_options; break; case PPP_IPV6CP: pfunc = print_ip6cp_config_options; break; case PPP_CCP: pfunc = print_ccp_config_options; break; case PPP_BACP: pfunc = print_bacp_config_options; break; default: /* * No print routine for the options for * this protocol. */ pfunc = NULL; break; } if (pfunc == NULL) /* catch the above null pointer if unknown CP */ break; if ((j = (*pfunc)(ndo, tptr, len)) == 0) break; x -= j; tptr += j; } while (x > 0); break; case CPCODES_TERM_REQ: case CPCODES_TERM_ACK: /* XXX: need to decode Data? */ break; case CPCODES_CODE_REJ: /* XXX: need to decode Rejected-Packet? */ break; case CPCODES_PROT_REJ: if (length < 6) break; ND_TCHECK2(*tptr, 2); ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)", tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); /* XXX: need to decode Rejected-Information? - hexdump for now */ if (len > 6) { ND_PRINT((ndo, "\n\t Rejected Packet")); print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2); } break; case CPCODES_ECHO_REQ: case CPCODES_ECHO_RPL: case CPCODES_DISC_REQ: if (length < 8) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); /* XXX: need to decode Data? - hexdump for now */ if (len > 8) { ND_PRINT((ndo, "\n\t -----trailing data-----")); ND_TCHECK2(tptr[4], len - 8); print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8); } break; case CPCODES_ID: if (length < 8) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); /* RFC 1661 says this is intended to be human readable */ if (len > 8) { ND_PRINT((ndo, "\n\t Message\n\t ")); if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend)) goto trunc; } break; case CPCODES_TIME_REM: if (length < 12) break; ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr))); ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4))); /* XXX: need to decode Message? */ break; default: /* XXX this is dirty but we do not get the * original pointer passed to the begin * the PPP packet */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2); break; } return; trunc: ND_PRINT((ndo, "[|%s]", typestr)); } /* LCP config options */ static int print_lcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", lcpconfopts[opt], opt, len)); else ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt)); return 0; } if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len)); else { ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt)); return len; } switch (opt) { case LCPOPT_VEXT: if (len < 6) { ND_PRINT((ndo, " (length bogus, should be >= 6)")); return len; } ND_TCHECK2(*(p + 2), 3); ND_PRINT((ndo, ": Vendor: %s (%u)", tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)), EXTRACT_24BITS(p + 2))); #if 0 ND_TCHECK(p[5]); ND_PRINT((ndo, ", kind: 0x%02x", p[5])); ND_PRINT((ndo, ", Value: 0x")); for (i = 0; i < len - 6; i++) { ND_TCHECK(p[6 + i]); ND_PRINT((ndo, "%02x", p[6 + i])); } #endif break; case LCPOPT_MRU: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return len; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2))); break; case LCPOPT_ACCM: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2))); break; case LCPOPT_AP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2)))); switch (EXTRACT_16BITS(p+2)) { case PPP_CHAP: ND_TCHECK(p[4]); ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4]))); break; case PPP_PAP: /* fall through */ case PPP_EAP: case PPP_SPAP: case PPP_SPAP_OLD: break; default: print_unknown_data(ndo, p, "\n\t", len); } break; case LCPOPT_QP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK2(*(p + 2), 2); if (EXTRACT_16BITS(p+2) == PPP_LQM) ND_PRINT((ndo, ": LQR")); else ND_PRINT((ndo, ": unknown")); break; case LCPOPT_MN: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2))); break; case LCPOPT_PFC: break; case LCPOPT_ACFC: break; case LCPOPT_LD: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return 0; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2))); break; case LCPOPT_CBACK: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return 0; } ND_PRINT((ndo, ": ")); ND_TCHECK(p[2]); ND_PRINT((ndo, ": Callback Operation %s (%u)", tok2str(ppp_callback_values, "Unknown", p[2]), p[2])); break; case LCPOPT_MLMRRU: if (len != 4) { ND_PRINT((ndo, " (length bogus, should be = 4)")); return 0; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2))); break; case LCPOPT_MLED: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return 0; } ND_TCHECK(p[2]); switch (p[2]) { /* class */ case MEDCLASS_NULL: ND_PRINT((ndo, ": Null")); break; case MEDCLASS_LOCAL: ND_PRINT((ndo, ": Local")); /* XXX */ break; case MEDCLASS_IPV4: if (len != 7) { ND_PRINT((ndo, " (length bogus, should be = 7)")); return 0; } ND_TCHECK2(*(p + 3), 4); ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3))); break; case MEDCLASS_MAC: if (len != 9) { ND_PRINT((ndo, " (length bogus, should be = 9)")); return 0; } ND_TCHECK2(*(p + 3), 6); ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3))); break; case MEDCLASS_MNB: ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */ break; case MEDCLASS_PSNDN: ND_PRINT((ndo, ": PSNDN")); /* XXX */ break; default: ND_PRINT((ndo, ": Unknown class %u", p[2])); break; } break; /* XXX: to be supported */ #if 0 case LCPOPT_DEP6: case LCPOPT_FCSALT: case LCPOPT_SDP: case LCPOPT_NUMMODE: case LCPOPT_DEP12: case LCPOPT_DEP14: case LCPOPT_DEP15: case LCPOPT_DEP16: case LCPOPT_MLSSNHF: case LCPOPT_PROP: case LCPOPT_DCEID: case LCPOPT_MPP: case LCPOPT_LCPAOPT: case LCPOPT_COBS: case LCPOPT_PE: case LCPOPT_MLHF: case LCPOPT_I18N: case LCPOPT_SDLOS: case LCPOPT_PPPMUX: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|lcp]")); return 0; } /* ML-PPP*/ static const struct tok ppp_ml_flag_values[] = { { 0x80, "begin" }, { 0x40, "end" }, { 0, NULL } }; static void handle_mlppp(netdissect_options *ndo, const u_char *p, int length) { if (!ndo->ndo_eflag) ND_PRINT((ndo, "MLPPP, ")); ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u", (EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */ bittok2str(ppp_ml_flag_values, "none", *p & 0xc0), length)); } /* CHAP */ static void handle_chap(netdissect_options *ndo, const u_char *p, int length) { u_int code, len; int val_size, name_size, msg_size; const u_char *p0; int i; p0 = p; if (length < 1) { ND_PRINT((ndo, "[|chap]")); return; } else if (length < 4) { ND_TCHECK(*p); ND_PRINT((ndo, "[|chap 0x%02x]", *p)); return; } ND_TCHECK(*p); code = *p; ND_PRINT((ndo, "CHAP, %s (0x%02x)", tok2str(chapcode_values,"unknown",code), code)); p++; ND_TCHECK(*p); ND_PRINT((ndo, ", id %u", *p)); /* ID */ p++; ND_TCHECK2(*p, 2); len = EXTRACT_16BITS(p); p += 2; /* * Note that this is a generic CHAP decoding routine. Since we * don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1, * MS-CHAPv2) is used at this point, we can't decode packet * specifically to each algorithms. Instead, we simply decode * the GCD (Gratest Common Denominator) for all algorithms. */ switch (code) { case CHAP_CHAL: case CHAP_RESP: if (length - (p - p0) < 1) return; ND_TCHECK(*p); val_size = *p; /* value size */ p++; if (length - (p - p0) < val_size) return; ND_PRINT((ndo, ", Value ")); for (i = 0; i < val_size; i++) { ND_TCHECK(*p); ND_PRINT((ndo, "%02x", *p++)); } name_size = len - (p - p0); ND_PRINT((ndo, ", Name ")); for (i = 0; i < name_size; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; case CHAP_SUCC: case CHAP_FAIL: msg_size = len - (p - p0); ND_PRINT((ndo, ", Msg ")); for (i = 0; i< msg_size; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; } return; trunc: ND_PRINT((ndo, "[|chap]")); } /* PAP (see RFC 1334) */ static void handle_pap(netdissect_options *ndo, const u_char *p, int length) { u_int code, len; int peerid_len, passwd_len, msg_len; const u_char *p0; int i; p0 = p; if (length < 1) { ND_PRINT((ndo, "[|pap]")); return; } else if (length < 4) { ND_TCHECK(*p); ND_PRINT((ndo, "[|pap 0x%02x]", *p)); return; } ND_TCHECK(*p); code = *p; ND_PRINT((ndo, "PAP, %s (0x%02x)", tok2str(papcode_values, "unknown", code), code)); p++; ND_TCHECK(*p); ND_PRINT((ndo, ", id %u", *p)); /* ID */ p++; ND_TCHECK2(*p, 2); len = EXTRACT_16BITS(p); p += 2; if ((int)len > length) { ND_PRINT((ndo, ", length %u > packet size", len)); return; } length = len; if (length < (p - p0)) { ND_PRINT((ndo, ", length %u < PAP header length", length)); return; } switch (code) { case PAP_AREQ: /* A valid Authenticate-Request is 6 or more octets long. */ if (len < 6) goto trunc; if (length - (p - p0) < 1) return; ND_TCHECK(*p); peerid_len = *p; /* Peer-ID Length */ p++; if (length - (p - p0) < peerid_len) return; ND_PRINT((ndo, ", Peer ")); for (i = 0; i < peerid_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } if (length - (p - p0) < 1) return; ND_TCHECK(*p); passwd_len = *p; /* Password Length */ p++; if (length - (p - p0) < passwd_len) return; ND_PRINT((ndo, ", Name ")); for (i = 0; i < passwd_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; case PAP_AACK: case PAP_ANAK: /* Although some implementations ignore truncation at * this point and at least one generates a truncated * packet, RFC 1334 section 2.2.2 clearly states that * both AACK and ANAK are at least 5 bytes long. */ if (len < 5) goto trunc; if (length - (p - p0) < 1) return; ND_TCHECK(*p); msg_len = *p; /* Msg-Length */ p++; if (length - (p - p0) < msg_len) return; ND_PRINT((ndo, ", Msg ")); for (i = 0; i< msg_len; i++) { ND_TCHECK(*p); safeputchar(ndo, *p++); } break; } return; trunc: ND_PRINT((ndo, "[|pap]")); } /* BAP */ static void handle_bap(netdissect_options *ndo _U_, const u_char *p _U_, int length _U_) { /* XXX: to be supported!! */ } /* IPCP config options */ static int print_ipcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ipcpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ipcpopt_values,"unknown",opt), opt, len)); switch (opt) { case IPCPOPT_2ADDR: /* deprecated */ if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 6), 4); ND_PRINT((ndo, ": src %s, dst %s", ipaddr_string(ndo, p + 2), ipaddr_string(ndo, p + 6))); break; case IPCPOPT_IPCOMP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK2(*(p + 2), 2); compproto = EXTRACT_16BITS(p+2); ND_PRINT((ndo, ": %s (0x%02x):", tok2str(ipcpopt_compproto_values, "Unknown", compproto), compproto)); switch (compproto) { case PPP_VJC: /* XXX: VJ-Comp parameters should be decoded */ break; case IPCPOPT_IPCOMP_HDRCOMP: if (len < IPCPOPT_IPCOMP_MINLEN) { ND_PRINT((ndo, " (length bogus, should be >= %u)", IPCPOPT_IPCOMP_MINLEN)); return 0; } ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN); ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \ ", maxPeriod %u, maxTime %u, maxHdr %u", EXTRACT_16BITS(p+4), EXTRACT_16BITS(p+6), EXTRACT_16BITS(p+8), EXTRACT_16BITS(p+10), EXTRACT_16BITS(p+12))); /* suboptions present ? */ if (len > IPCPOPT_IPCOMP_MINLEN) { ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN; p += IPCPOPT_IPCOMP_MINLEN; ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen)); while (ipcomp_subopttotallen >= 2) { ND_TCHECK2(*p, 2); ipcomp_subopt = *p; ipcomp_suboptlen = *(p+1); /* sanity check */ if (ipcomp_subopt == 0 || ipcomp_suboptlen == 0 ) break; /* XXX: just display the suboptions for now */ ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u", tok2str(ipcpopt_compproto_subopt_values, "Unknown", ipcomp_subopt), ipcomp_subopt, ipcomp_suboptlen)); ipcomp_subopttotallen -= ipcomp_suboptlen; p += ipcomp_suboptlen; } } break; default: break; } break; case IPCPOPT_ADDR: /* those options share the same format - fall through */ case IPCPOPT_MOBILE4: case IPCPOPT_PRIDNS: case IPCPOPT_PRINBNS: case IPCPOPT_SECDNS: case IPCPOPT_SECNBNS: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ipcp]")); return 0; } /* IP6CP config options */ static int print_ip6cp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ip6cpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ip6cpopt_values,"unknown",opt), opt, len)); switch (opt) { case IP6CP_IFID: if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 2), 8); ND_PRINT((ndo, ": %04x:%04x:%04x:%04x", EXTRACT_16BITS(p + 2), EXTRACT_16BITS(p + 4), EXTRACT_16BITS(p + 6), EXTRACT_16BITS(p + 8))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ip6cp]")); return 0; } /* CCP config options */ static int print_ccp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case CCPOPT_BSDCOMP: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u", p[2] >> 5, p[2] & 0x1f)); break; case CCPOPT_MVRCA: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u", (p[2] & 0xc0) >> 6, (p[2] & 0x20) ? "Enabled" : "Disabled", p[2] & 0x1f, p[3])); break; case CCPOPT_DEFLATE: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u", (p[2] & 0xf0) >> 4, ((p[2] & 0x0f) == 8) ? "zlib" : "unknown", p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); break; /* XXX: to be supported */ #if 0 case CCPOPT_OUI: case CCPOPT_PRED1: case CCPOPT_PRED2: case CCPOPT_PJUMP: case CCPOPT_HPPPC: case CCPOPT_STACLZS: case CCPOPT_MPPC: case CCPOPT_GFZA: case CCPOPT_V42BIS: case CCPOPT_LZSDCP: case CCPOPT_DEC: case CCPOPT_RESV: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ccp]")); return 0; } /* BACP config options */ static int print_bacp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case BACPOPT_FPEER: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|bacp]")); return 0; } static void ppp_hdlc(netdissect_options *ndo, const u_char *p, int length) { u_char *b, *t, c; const u_char *s; int i, proto; const void *se; if (length <= 0) return; b = (u_char *)malloc(length); if (b == NULL) return; /* * Unescape all the data into a temporary, private, buffer. * Do this so that we dont overwrite the original packet * contents. */ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { c = *s++; if (c == 0x7d) { if (i <= 1 || !ND_TTEST(*s)) break; i--; c = *s++ ^ 0x20; } *t++ = c; } se = ndo->ndo_snapend; ndo->ndo_snapend = t; length = t - b; /* now lets guess about the payload codepoint format */ if (length < 1) goto trunc; proto = *b; /* start with a one-octet codepoint guess */ switch (proto) { case PPP_IP: ip_print(ndo, b + 1, length - 1); goto cleanup; case PPP_IPV6: ip6_print(ndo, b + 1, length - 1); goto cleanup; default: /* no luck - try next guess */ break; } if (length < 2) goto trunc; proto = EXTRACT_16BITS(b); /* next guess - load two octets */ switch (proto) { case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */ if (length < 4) goto trunc; proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */ handle_ppp(ndo, proto, b + 4, length - 4); break; default: /* last guess - proto must be a PPP proto-id */ handle_ppp(ndo, proto, b + 2, length - 2); break; } cleanup: ndo->ndo_snapend = se; free(b); return; trunc: ndo->ndo_snapend = se; free(b); ND_PRINT((ndo, "[|ppp]")); } /* PPP */ static void handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } } /* Standard PPP printer */ u_int ppp_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto,ppp_header; u_int olen = length; /* _o_riginal length */ u_int hdr_len = 0; /* * Here, we assume that p points to the Address and Control * field (if they present). */ if (length < 2) goto trunc; ND_TCHECK2(*p, 2); ppp_header = EXTRACT_16BITS(p); switch(ppp_header) { case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL): if (ndo->ndo_eflag) ND_PRINT((ndo, "In ")); p += 2; length -= 2; hdr_len += 2; break; case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL): if (ndo->ndo_eflag) ND_PRINT((ndo, "Out ")); p += 2; length -= 2; hdr_len += 2; break; case (PPP_ADDRESS << 8 | PPP_CONTROL): p += 2; /* ACFC not used */ length -= 2; hdr_len += 2; break; default: break; } if (length < 2) goto trunc; ND_TCHECK(*p); if (*p % 2) { proto = *p; /* PFC is used */ p++; length--; hdr_len++; } else { ND_TCHECK2(*p, 2); proto = EXTRACT_16BITS(p); p += 2; length -= 2; hdr_len += 2; } if (ndo->ndo_eflag) ND_PRINT((ndo, "%s (0x%04x), length %u: ", tok2str(ppptype2str, "unknown", proto), proto, olen)); handle_ppp(ndo, proto, p, length); return (hdr_len); trunc: ND_PRINT((ndo, "[|ppp]")); return (0); } /* PPP I/F printer */ u_int ppp_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; if (caplen < PPP_HDRLEN) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } #if 0 /* * XXX: seems to assume that there are 2 octets prepended to an * actual PPP frame. The 1st octet looks like Input/Output flag * while 2nd octet is unknown, at least to me * (mshindo@mshindo.net). * * That was what the original tcpdump code did. * * FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound * packets and 0 for inbound packets - but only if the * protocol field has the 0x8000 bit set (i.e., it's a network * control protocol); it does so before running the packet through * "bpf_filter" to see if it should be discarded, and to see * if we should update the time we sent the most recent packet... * * ...but it puts the original address field back after doing * so. * * NetBSD's "if_ppp.c" doesn't set the first octet in that fashion. * * I don't know if any PPP implementation handed up to a BPF * device packets with the first octet being 1 for outbound and * 0 for inbound packets, so I (guy@alum.mit.edu) don't know * whether that ever needs to be checked or not. * * Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP, * and its tcpdump appears to assume that the frame always * begins with an address field and a control field, and that * the address field might be 0x0f or 0x8f, for Cisco * point-to-point with HDLC framing as per section 4.3.1 of RFC * 1547, as well as 0xff, for PPP in HDLC-like framing as per * RFC 1662. * * (Is the Cisco framing in question what DLT_C_HDLC, in * BSD/OS, is?) */ if (ndo->ndo_eflag) ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1])); #endif ppp_print(ndo, p, length); return (0); } /* * PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like * framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547, * is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL, * discard them *if* those are the first two octets, and parse the remaining * packet as a PPP packet, as "ppp_print()" does). * * This handles, for example, DLT_PPP_SERIAL in NetBSD. */ u_int ppp_hdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; u_int proto; u_int hdrlen = 0; if (caplen < 2) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } switch (p[0]) { case PPP_ADDRESS: if (caplen < 4) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length)); p += 2; length -= 2; hdrlen += 2; proto = EXTRACT_16BITS(p); p += 2; length -= 2; hdrlen += 2; ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); handle_ppp(ndo, proto, p, length); break; case CHDLC_UNICAST: case CHDLC_BCAST: return (chdlc_if_print(ndo, h, p)); default: if (caplen < 4) { ND_PRINT((ndo, "[|ppp]")); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length)); p += 2; hdrlen += 2; /* * XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats * the next two octets as an Ethernet type; does that * ever happen? */ ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1])); break; } return (hdrlen); } #define PPP_BSDI_HDRLEN 24 /* BSD/OS specific PPP printer */ u_int ppp_bsdos_if_print(netdissect_options *ndo _U_, const struct pcap_pkthdr *h _U_, register const u_char *p _U_) { register int hdrlength; #ifdef __bsdi__ register u_int length = h->len; register u_int caplen = h->caplen; uint16_t ptype; const u_char *q; int i; if (caplen < PPP_BSDI_HDRLEN) { ND_PRINT((ndo, "[|ppp]")); return (caplen) } hdrlength = 0; #if 0 if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) { if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x ", p[0], p[1])); p += 2; hdrlength = 2; } if (ndo->ndo_eflag) ND_PRINT((ndo, "%d ", length)); /* Retrieve the protocol type */ if (*p & 01) { /* Compressed protocol field */ ptype = *p; if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x ", ptype)); p++; hdrlength += 1; } else { /* Un-compressed protocol field */ ptype = EXTRACT_16BITS(p); if (ndo->ndo_eflag) ND_PRINT((ndo, "%04x ", ptype)); p += 2; hdrlength += 2; } #else ptype = 0; /*XXX*/ if (ndo->ndo_eflag) ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I')); if (p[SLC_LLHL]) { /* link level header */ struct ppp_header *ph; q = p + SLC_BPFHDRLEN; ph = (struct ppp_header *)q; if (ph->phdr_addr == PPP_ADDRESS && ph->phdr_ctl == PPP_CONTROL) { if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x %02x ", q[0], q[1])); ptype = EXTRACT_16BITS(&ph->phdr_type); if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) { ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "proto-#%d", ptype))); } } else { if (ndo->ndo_eflag) { ND_PRINT((ndo, "LLH=[")); for (i = 0; i < p[SLC_LLHL]; i++) ND_PRINT((ndo, "%02x", q[i])); ND_PRINT((ndo, "] ")); } } } if (ndo->ndo_eflag) ND_PRINT((ndo, "%d ", length)); if (p[SLC_CHL]) { q = p + SLC_BPFHDRLEN + p[SLC_LLHL]; switch (ptype) { case PPP_VJC: ptype = vjc_print(ndo, q, ptype); hdrlength = PPP_BSDI_HDRLEN; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(ndo, p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; } goto printx; case PPP_VJNC: ptype = vjc_print(ndo, q, ptype); hdrlength = PPP_BSDI_HDRLEN; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(ndo, p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; } goto printx; default: if (ndo->ndo_eflag) { ND_PRINT((ndo, "CH=[")); for (i = 0; i < p[SLC_LLHL]; i++) ND_PRINT((ndo, "%02x", q[i])); ND_PRINT((ndo, "] ")); } break; } } hdrlength = PPP_BSDI_HDRLEN; #endif length -= hdrlength; p += hdrlength; switch (ptype) { case PPP_IP: ip_print(p, length); break; case PPP_IPV6: ip6_print(ndo, p, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype))); } printx: #else /* __bsdi */ hdrlength = 0; #endif /* __bsdi__ */ return (hdrlength); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_11
crossvul-cpp_data_good_2748_0
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2748_0
crossvul-cpp_data_good_3974_0
/* * ssh.c * * Copyright (C) 2009-2011 by ipoque GmbH * Copyright (C) 2011-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI 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 3 of the License, or * (at your option) any later version. * * nDPI 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 nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_SSH #include "ndpi_api.h" #include "ndpi_md5.h" /* HASSH - https://github.com/salesforce/hassh https://github.com/salesforce/hassh/blob/master/python/hassh.py [server] skex = packet.ssh.kex_algorithms seastc = packet.ssh.encryption_algorithms_server_to_client smastc = packet.ssh.mac_algorithms_server_to_client scastc = packet.ssh.compression_algorithms_server_to_client hasshs_str = ';'.join([skex, seastc, smastc, scastc]) [client] ckex = packet.ssh.kex_algorithms ceacts = packet.ssh.encryption_algorithms_client_to_server cmacts = packet.ssh.mac_algorithms_client_to_server ccacts = packet.ssh.compression_algorithms_client_to_server hassh_str = ';'.join([ckex, ceacts, cmacts, ccacts]) NOTE THe ECDSA key fingerprint is SHA256 -> ssh.kex.h_sig (wireshark) is in the Message Code: Diffie-Hellman Key Exchange Reply (31) that usually is packet 14 */ /* #define SSH_DEBUG 1 */ static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* ************************************************************************ */ static int search_ssh_again(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { ndpi_search_ssh_tcp(ndpi_struct, flow); if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) { /* stop extra processing */ flow->extra_packets_func = NULL; /* We're good now */ return(0); } /* Possibly more processing */ return(1); } /* ************************************************************************ */ static void ndpi_int_ssh_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { if(flow->extra_packets_func != NULL) return; flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH; /* This is necessary to inform the core to call this dissector again */ flow->check_extra_packets = 1; flow->max_extra_packets_to_check = 12; flow->extra_packets_func = search_ssh_again; ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_SSH, NDPI_PROTOCOL_UNKNOWN); } /* ************************************************************************ */ static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet, char *buf, u_int8_t client_hash) { u_int16_t offset = 22, buf_out_len = 0; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; /* -1 for ';' */ if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; /* ssh.kex_algorithms [C/S] */ strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len); buf[buf_out_len++] = ';'; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.server_host_key_algorithms [None] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_client_to_server [C] */ if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.compression_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.languages_client_to_server [None] */ /* ssh.languages_server_to_client [None] */ #ifdef SSH_DEBUG printf("[SSH] %s\n", buf); #endif return(buf_out_len); invalid_payload: #ifdef SSH_DEBUG printf("[SSH] Invalid packet payload\n"); #endif return(0); } /* ************************************************************************ */ static void ndpi_ssh_zap_cr(char *str, int len) { len--; while(len > 0) { if((str[len] == '\n') || (str[len] == '\r')) { str[len] = '\0'; len--; } else break; } } /* ************************************************************************ */ static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef SSH_DEBUG printf("[SSH] %s()\n", __FUNCTION__); #endif if(flow->l4.tcp.ssh_stage == 0) { if(packet->payload_packet_len > 7 && packet->payload_packet_len < 100 && memcmp(packet->payload, "SSH-", 4) == 0) { int len = ndpi_min(sizeof(flow->protos.ssh.client_signature)-1, packet->payload_packet_len); strncpy(flow->protos.ssh.client_signature, (const char *)packet->payload, len); flow->protos.ssh.client_signature[len] = '\0'; ndpi_ssh_zap_cr(flow->protos.ssh.client_signature, len); #ifdef SSH_DEBUG printf("[SSH] [client_signature: %s]\n", flow->protos.ssh.client_signature); #endif NDPI_LOG_DBG2(ndpi_struct, "ssh stage 0 passed\n"); flow->l4.tcp.ssh_stage = 1 + packet->packet_direction; ndpi_int_ssh_add_connection(ndpi_struct, flow); return; } } else if(flow->l4.tcp.ssh_stage == (2 - packet->packet_direction)) { if(packet->payload_packet_len > 7 && packet->payload_packet_len < 500 && memcmp(packet->payload, "SSH-", 4) == 0) { int len = ndpi_min(sizeof(flow->protos.ssh.server_signature)-1, packet->payload_packet_len); strncpy(flow->protos.ssh.server_signature, (const char *)packet->payload, len); flow->protos.ssh.server_signature[len] = '\0'; ndpi_ssh_zap_cr(flow->protos.ssh.server_signature, len); #ifdef SSH_DEBUG printf("[SSH] [server_signature: %s]\n", flow->protos.ssh.server_signature); #endif NDPI_LOG_DBG2(ndpi_struct, "ssh stage 1 passed\n"); flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH; #ifdef SSH_DEBUG printf("[SSH] [completed stage: %u]\n", flow->l4.tcp.ssh_stage); #endif flow->l4.tcp.ssh_stage = 3; return; } } else if(packet->payload_packet_len > 5) { u_int8_t msgcode = *(packet->payload + 5); ndpi_MD5_CTX ctx; if(msgcode == 20 /* key exchange init */) { char *hassh_buf = ndpi_calloc(packet->payload_packet_len, sizeof(char)); u_int i, len; #ifdef SSH_DEBUG printf("[SSH] [stage: %u][msg: %u][direction: %u][key exchange init]\n", flow->l4.tcp.ssh_stage, msgcode, packet->packet_direction); #endif if(hassh_buf) { if(packet->packet_direction == 0 /* client */) { u_char fingerprint_client[16]; len = concat_hash_string(packet, hassh_buf, 1 /* client */); ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len); ndpi_MD5Final(fingerprint_client, &ctx); #ifdef SSH_DEBUG { printf("[SSH] [client][%s][", hassh_buf); for(i=0; i<16; i++) printf("%02X", fingerprint_client[i]); printf("]\n"); } #endif for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_client[i*2], "%02X", fingerprint_client[i] & 0xFF); flow->protos.ssh.hassh_client[32] = '\0'; } else { u_char fingerprint_server[16]; len = concat_hash_string(packet, hassh_buf, 0 /* server */); ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len); ndpi_MD5Final(fingerprint_server, &ctx); #ifdef SSH_DEBUG { printf("[SSH] [server][%s][", hassh_buf); for(i=0; i<16; i++) printf("%02X", fingerprint_server[i]); printf("]\n"); } #endif for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_server[i*2], "%02X", fingerprint_server[i] & 0xFF); flow->protos.ssh.hassh_server[32] = '\0'; } ndpi_free(hassh_buf); } ndpi_int_ssh_add_connection(ndpi_struct, flow); } if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) { #ifdef SSH_DEBUG printf("[SSH] Dissection completed\n"); #endif flow->extra_packets_func = NULL; /* We're good now */ } return; } #ifdef SSH_DEBUG printf("[SSH] Excluding SSH"); #endif NDPI_LOG_DBG(ndpi_struct, "excluding ssh at stage %d\n", flow->l4.tcp.ssh_stage); NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_SSH); } /* ************************************************************************ */ void init_ssh_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("SSH", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_SSH, ndpi_search_ssh_tcp, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3974_0
crossvul-cpp_data_good_351_1
/* * Copyright (c) 2007 Athena Smartcard Solutions Inc. * * 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 <string.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static const struct sc_card_operations *iso_ops = NULL; struct sc_card_operations asepcos_ops; static struct sc_card_driver asepcos_drv = { "Athena ASEPCOS", "asepcos", &asepcos_ops, NULL, 0, NULL }; static struct sc_atr_table asepcos_atrs[] = { { "3b:d6:18:00:81:b1:80:7d:1f:03:80:51:00:61:10:30:8f", NULL, NULL, SC_CARD_TYPE_ASEPCOS_GENERIC, 0, NULL}, { "3b:d6:18:00:81:b1:fe:7d:1f:03:41:53:45:37:35:35:01", NULL, NULL, SC_CARD_TYPE_ASEPCOS_JAVA, 0, NULL}, { NULL, NULL, NULL, 0, 0, NULL } }; static int asepcos_match_card(sc_card_t *card) { int i = _sc_match_atr(card, asepcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int asepcos_select_asepcos_applet(sc_card_t *card) { static const u8 asepcos_aid[] = {0xA0,0x00,0x00,0x01,0x64,0x41,0x53,0x45,0x50,0x43,0x4F,0x53,0x00}; sc_path_t tpath; int r; memset(&tpath, 0, sizeof(sc_path_t)); tpath.type = SC_PATH_TYPE_DF_NAME; tpath.len = sizeof(asepcos_aid); memcpy(tpath.value, asepcos_aid, sizeof(asepcos_aid)); r = sc_select_file(card, &tpath, NULL); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to select ASEPCOS applet"); return r; } return SC_SUCCESS; } static int asepcos_init(sc_card_t *card) { unsigned long flags; card->name = "Athena ASEPCOS"; card->cla = 0x00; /* in case of a Java card try to select the ASEPCOS applet */ if (card->type == SC_CARD_TYPE_ASEPCOS_JAVA) { int r = asepcos_select_asepcos_applet(card); if (r != SC_SUCCESS) return SC_ERROR_INVALID_CARD; } /* Set up algorithm info. */ flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_ONBOARD_KEY_GEN ; _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, 1536, flags, 0); _sc_card_add_rsa_alg(card, 1792, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); card->caps |= SC_CARD_CAP_APDU_EXT | SC_CARD_CAP_USE_FCI_AC; return SC_SUCCESS; } /* tables to map the asepcos access mode bytes to the OpenSC * access mode flags */ typedef struct { unsigned int am; unsigned int sc; } amode_entry_t; static const amode_entry_t df_amode_table[] = { { 0x40, SC_AC_OP_DELETE_SELF }, /* DELETE self */ { 0x01, SC_AC_OP_DELETE }, /* DELETE child */ { 0x10, SC_AC_OP_INVALIDATE }, /* DEACTIVATE FILE */ { 0x08, SC_AC_OP_REHABILITATE },/* ACTIVATE FILE */ { 0x04, SC_AC_OP_CREATE }, /* CREATE DF */ { 0x02, SC_AC_OP_CREATE }, /* CREATE EF */ { 0, 0 } }; static const amode_entry_t wef_amode_table[] = { { 0x04, SC_AC_OP_WRITE }, { 0x02, SC_AC_OP_UPDATE }, { 0x01, SC_AC_OP_READ }, { 0, 0 }, }; static const amode_entry_t ief_amode_table[] = { { 0x90, SC_AC_OP_REHABILITATE }, /* UPDATE is also used when a new key is generated */ { 0x82, SC_AC_OP_UPDATE }, { 0, 0 }, }; static int set_sec_attr(sc_file_t *file, unsigned int am, unsigned int ac, unsigned int meth) { const amode_entry_t *table; /* CHV with reference '0' is the transport PIN * and is presented as 'AUT' key with reference '0'*/ if (meth == SC_AC_CHV && ac == 0) meth = SC_AC_AUT; if (file->type == SC_FILE_TYPE_DF) table = df_amode_table; else if (file->type == SC_FILE_TYPE_WORKING_EF) table = wef_amode_table; else if (file->type == SC_FILE_TYPE_INTERNAL_EF) table = ief_amode_table; else return SC_ERROR_INVALID_ARGUMENTS; for (; table->am != 0; table++) { if (table->am & am) sc_file_add_acl_entry(file, table->sc, meth, ac); } return SC_SUCCESS; } /* Convert asepcos security attributes to opensc access conditions. */ static int asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { const u8 *p = buf; while (len != 0) { unsigned int amode, tlen = 3; if (len < 5 || p[0] != 0x80 || p[1] != 0x01) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding"); return SC_ERROR_INTERNAL; } amode = p[2]; if (p[3] == 0x90 && p[4] == 0x00) { int r = set_sec_attr(file, amode, 0, SC_AC_NONE); if (r != SC_SUCCESS) return r; tlen += 2; } else if (p[3] == 0x97 && p[4] == 0x00) { int r = set_sec_attr(file, amode, 0, SC_AC_NEVER); if (r != SC_SUCCESS) return r; tlen += 2; } else if (p[3] == 0xA0 && len >= 4U + p[4]) { /* TODO: support OR expressions */ int r = set_sec_attr(file, amode, p[5], SC_AC_CHV); if (r != SC_SUCCESS) return r; tlen += 2 + p[4]; /* FIXME */ } else if (p[3] == 0xAF && len >= 4U + p[4]) { /* TODO: support AND expressions */ int r = set_sec_attr(file, amode, p[5], SC_AC_CHV); if (r != SC_SUCCESS) return r; tlen += 2 + p[4]; /* FIXME */ } else { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition"); return SC_ERROR_INTERNAL; } p += tlen; len -= tlen; } return SC_SUCCESS; } /* sets a TLV encoded path as returned from GET DATA in a sc_path_t object */ static int asepcos_tlvpath_to_scpath(sc_path_t *out, const u8 *in, size_t in_len) { int r; size_t len = in_len; memset(out, 0, sizeof(sc_path_t)); while (len != 0) { if (len < 4) return SC_ERROR_INTERNAL; if (in[0] != 0x8b || in[1] != 0x02) return SC_ERROR_INVALID_ASN1_OBJECT; /* append file id to the path */ r = sc_append_path_id(out, &in[2], 2); if (r != SC_SUCCESS) return r; len -= 4; in += 4; } out->type = SC_PATH_TYPE_PATH; return SC_SUCCESS; } /* returns the currently selected DF (if a EF is currently selected * it returns the path from the MF to the DF in which the EF is * located. * @param card sc_card_t object to use * @param path OUT path from the MF to the current DF * @return SC_SUCCESS on success and an error value otherwise */ static int asepcos_get_current_df_path(sc_card_t *card, sc_path_t *path) { int r; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x83); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return sc_check_sw(card, apdu.sw1, apdu.sw2); return asepcos_tlvpath_to_scpath(path, apdu.resp, apdu.resplen); } /* SELECT FILE: call the ISO SELECT FILE implementation and parse * asepcos specific security attributes. */ static int asepcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file) { int r; sc_path_t npath = *in_path; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (in_path->type == SC_PATH_TYPE_PATH) { /* check the current DF to avoid unnecessary re-selection of * the MF (as this might invalidate a security status) */ sc_path_t tpath; r = asepcos_get_current_df_path(card, &tpath); /* workaround: as opensc can't handle paths with file id * and application names in it let's ignore the current * DF if the returned path contains a unsupported tag. */ if (r != SC_ERROR_INVALID_ASN1_OBJECT && r != SC_SUCCESS) return r; if (r == SC_SUCCESS && sc_compare_path_prefix(&tpath, &npath) != 0) { /* remove the currently selected DF from the path */ if (tpath.len == npath.len) { /* we are already in the requested DF */ if (file == NULL) /* no file information requested => * nothing to do */ return SC_SUCCESS; } else { /* shorten path */ r = sc_path_set(&npath, 0, &in_path->value[tpath.len], npath.len - tpath.len, 0, 0); if (r != SC_SUCCESS) return r; if (npath.len == 2) npath.type = SC_PATH_TYPE_FILE_ID; else npath.type = SC_PATH_TYPE_PATH; } } } r = iso_ops->select_file(card, &npath, file); /* XXX: this doesn't look right */ if (file != NULL && *file != NULL) if ((*file)->ef_structure == SC_FILE_EF_UNKNOWN) (*file)->ef_structure = SC_FILE_EF_TRANSPARENT; if (r == SC_SUCCESS && file != NULL && *file != NULL) { r = asepcos_parse_sec_attr(card, *file, (*file)->sec_attr, (*file)->sec_attr_len); if (r != SC_SUCCESS) sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "error parsing security attributes"); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int asepcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { return SC_SUCCESS; } static int asepcos_akn_to_fileid(sc_card_t *card, sc_cardctl_asepcos_akn2fileid_t *p) { int r; u8 sbuf[32], rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; sbuf[0] = p->akn & 0xff; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x28, 0x02, 0x01); apdu.cla |= 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; apdu.lc = 1; apdu.datalen = 1; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.resplen != 4) return SC_ERROR_INTERNAL; p->fileid = (apdu.resp[1] << 16) | (apdu.resp[2] << 8) | apdu.resp[3]; return SC_SUCCESS; } /* sets the security attribute of a EF/DF */ static int asepcos_set_sec_attributes(sc_card_t *card, const u8 *data, size_t len, int is_ef) { int r, type = is_ef != 0 ? 0x02 : 0x04; sc_apdu_t apdu; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x8a, type, 0xab); apdu.cla |= 0x80; apdu.lc = len; apdu.datalen = len; apdu.data = data; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } /* encodes the opensc file attributes into the card specific format */ static int asepcos_set_security_attributes(sc_card_t *card, sc_file_t *file) { size_t i; const amode_entry_t *table; u8 buf[64], *p; int r = SC_SUCCESS; /* first check whether the security attributes in encoded form * are already set. If present use these */ if (file->sec_attr != NULL && file->sec_attr_len != 0) return asepcos_set_sec_attributes(card, file->sec_attr, file->sec_attr_len, file->type == SC_FILE_TYPE_DF ? 0:1); /* otherwise construct the ACL from the opensc ACLs */ if (file->type == SC_FILE_TYPE_DF) table = df_amode_table; else if (file->type == SC_FILE_TYPE_WORKING_EF) table = wef_amode_table; else if (file->type == SC_FILE_TYPE_INTERNAL_EF) table = ief_amode_table; else return SC_ERROR_INVALID_ARGUMENTS; p = buf; for (i = 0; table[i].am != 0; i++) { const struct sc_acl_entry *ent = sc_file_get_acl_entry(file, table[i].sc); if (ent == NULL) continue; *p++ = 0x80; *p++ = 0x01; *p++ = table[i].am & 0xff; if (ent->method == SC_AC_NONE) { *p++ = 0x90; *p++ = 0x00; } else if (ent->method == SC_AC_NEVER) { *p++ = 0x97; *p++ = 0x00; } else if (ent->method == SC_AC_CHV) { sc_cardctl_asepcos_akn2fileid_t st; st.akn = ent->key_ref; r = asepcos_akn_to_fileid(card, &st); if (r != SC_SUCCESS) return r; *p++ = 0xa0; *p++ = 0x05; *p++ = 0x89; *p++ = 0x03; *p++ = (st.fileid >> 16) & 0xff; *p++ = (st.fileid >> 8 ) & 0xff; *p++ = st.fileid & 0xff; } else { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unknown auth method: '%d'", ent->method); return SC_ERROR_INTERNAL; } } if (p != buf) r = asepcos_set_sec_attributes(card, buf, p-buf, file->type == SC_FILE_TYPE_DF ? 0:1); return r; } static int asepcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); /* call RSA ENCRYPT DECRYPT for the decipher operation */ sc_format_apdu(card, &apdu, SC_APDU_CASE_4, 0x14, 0x01, 0x00); apdu.cla |= 0x80; apdu.resp = out; apdu.resplen = outlen; /* if less than 256 bytes are expected than set Le to 0x00 * to tell the card the we want everything available (note: we * always have Le <= crgram_len) */ apdu.le = (outlen >= 256 && crgram_len < 256) ? 256 : outlen; apdu.data = crgram; apdu.lc = crgram_len; apdu.datalen = crgram_len; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); return apdu.resplen; } /* compute the signature. Currently the RSA ENCRYPT DECRYPT command * is used here (TODO: use the key attributes to determine method * to use for signature generation). */ static int asepcos_compute_signature(sc_card_t *card, const u8 *data, size_t datalen, u8 *out, size_t outlen) { int r = SC_SUCCESS, atype; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (datalen >= 256) atype = SC_APDU_CASE_4_EXT; else atype = SC_APDU_CASE_4_SHORT; sc_format_apdu(card, &apdu, atype, 0x14, 0x01, 0x00); apdu.cla |= 0x80; apdu.lc = datalen; apdu.datalen = datalen; apdu.data = data; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "error creating signature"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.resplen > outlen) return SC_ERROR_BUFFER_TOO_SMALL; memcpy(out, apdu.resp, apdu.resplen); return apdu.resplen; } /* activates the EF/DF specified in the file id. */ static int asepcos_activate_file(sc_card_t *card, int fileid, int is_ef) { int r, type = is_ef != 0 ? 2 : 1; sc_apdu_t apdu; u8 sbuf[2]; sbuf[0] = (fileid >> 8) & 0xff; sbuf[1] = fileid & 0xff; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x44, type, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } /* CREATE FILE: creates wEF, iEF and DFs. Note: although the ISO * command is used for wEF and iEF so format of the data send to * the card is asepcos specific. * @param card the sc_card_t object to use * @param file sc_file_t object describing the file to create * @return SC_SUCCESS on success and an error code otherwise. */ static int asepcos_create_file(sc_card_t *card, sc_file_t *file) { if (file->type == SC_FILE_TYPE_DF) { int r, type; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p = &sbuf[0]; *p++ = (file->id >> 8) & 0xff; *p++ = file->id & 0xff; if (file->size > 0xffff) { *p++ = (file->size >> 24) & 0xff; *p++ = (file->size >> 16) & 0xff; *p++ = (file->size >> 8 ) & 0xff; *p++ = file->size & 0xff; type = 1; } else { *p++ = (file->size >> 8) & 0xff; *p++ = file->size & 0xff; type = 0; } if (file->namelen != 0 && file->namelen <= 16) { memcpy(p, file->name, file->namelen); p += file->namelen; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe0, 0x38, type); apdu.cla |= 0x80; apdu.lc = p - sbuf; apdu.datalen = p - sbuf; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return sc_check_sw(card, apdu.sw1, apdu.sw2); r = sc_select_file(card, &file->path, NULL); if (r != SC_SUCCESS) return r; /* set security attributes */ r = asepcos_set_security_attributes(card, file); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to set security attributes"); return r; } return SC_SUCCESS; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { int r; sc_apdu_t apdu; u8 descr_byte = file->ef_structure & 7; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p = &sbuf[0]; *p++ = 0x85; p++; /* file id */ *p++ = (file->id >> 8) & 0xff; *p++ = file->id & 0xff; /* record size */ if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { *p++ = 0x00; *p++ = 0x00; } else { *p++ = (file->record_length >> 8) & 0xff; *p++ = file->record_length & 0xff; } /* number of records or file size */ if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { *p++ = (file->size >> 8) & 0xff; *p++ = file->size & 0xff; } else { *p++ = (file->record_count >> 8) & 0xff; *p++ = file->record_count & 0xff; } /* set the length of the inner TLV object */ sbuf[1] = p - sbuf - 2; /* FIXME */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe0, descr_byte, 0x00); apdu.lc = p - sbuf; apdu.datalen = p - sbuf; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return sc_check_sw(card, apdu.sw1, apdu.sw2); /* set security attributes */ r = asepcos_set_security_attributes(card, file); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to set security attributes"); return r; } return asepcos_activate_file(card, file->id, 1); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { /* for internal EF we 'misuse' the prop_attr field of the * sc_file_t object to store the data send to the card in * the CREATE EF call. */ int r, atype = SC_APDU_CASE_3_SHORT; sc_apdu_t apdu; if (file->prop_attr_len > 255) atype = SC_APDU_CASE_3_EXT; sc_format_apdu(card, &apdu, atype, 0xe0, 0x08, 0x00); apdu.lc = file->prop_attr_len; apdu.datalen = file->prop_attr_len; apdu.data = file->prop_attr; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return sc_check_sw(card, apdu.sw1, apdu.sw2); /* set security attributes */ r = asepcos_set_security_attributes(card, file); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to set security attributes"); return r; } return asepcos_activate_file(card, file->id, 1); } else return SC_ERROR_INVALID_ARGUMENTS; } /* list files: the function first calls GET DATA to get the current * working DF. It then re-selects the DF to get proprietary FCI which * contain the FID of the first child DF EF. * The FID of the other EFs/DFs within the selected DF are then * obtained by selecting the know FIDs to get next child EF/DF. * @param card the sc_card_t object to use * @param buff the output buffer for the list of FIDs * @param blen the length of the buffer * @return the number of FIDs read on success and an error value otherwise. */ static int asepcos_list_files(sc_card_t *card, u8 *buf, size_t blen) { int r, rv = 0, dfFID, efFID; sc_path_t bpath, tpath; sc_file_t *tfile = NULL; /* 1. get currently selected DF */ r = asepcos_get_current_df_path(card, &bpath); if (r != SC_SUCCESS) return r; /* 2. re-select DF to get the FID of the child EFs/DFs */ r = sc_select_file(card, &bpath, &tfile); if (r != SC_SUCCESS) return r; if (tfile->prop_attr_len != 6 || tfile->prop_attr == NULL) { sc_file_free(tfile); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to parse proprietary FCI attributes"); return SC_ERROR_INTERNAL; } dfFID = (tfile->prop_attr[2] << 8) | tfile->prop_attr[3]; efFID = (tfile->prop_attr[4] << 8) | tfile->prop_attr[5]; sc_file_free(tfile); /* 3. select every child DF to get the FID of the next child DF */ while (dfFID != 0) { /* put DF FID on the list */ if (blen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *buf++ = (dfFID >> 8) & 0xff; *buf++ = dfFID & 0xff; rv += 2; blen -= 2; /* select DF to get next DF FID */ tpath = bpath; r = sc_append_file_id(&tpath, dfFID); if (r != SC_SUCCESS) return r; r = sc_select_file(card, &tpath, &tfile); if (r != SC_SUCCESS) return r; if (tfile->prop_attr_len != 6 || tfile->prop_attr == NULL) return SC_ERROR_INTERNAL; dfFID = (tfile->prop_attr[0] << 8) | tfile->prop_attr[1]; sc_file_free(tfile); } /* 4. select every child EF ... */ while (efFID != 0) { /* put DF FID on the list */ if (blen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *buf++ = (efFID >> 8) & 0xff; *buf++ = efFID & 0xff; rv += 2; blen -= 2; /* select EF to get next EF FID */ tpath = bpath; r = sc_append_file_id(&tpath, efFID); if (r != SC_SUCCESS) return r; r = sc_select_file(card, &tpath, &tfile); if (r != SC_SUCCESS) return r; if (tfile->prop_attr_len < 2 || tfile->prop_attr == NULL) return SC_ERROR_INTERNAL; efFID = (tfile->prop_attr[0] << 8) | tfile->prop_attr[1]; sc_file_free(tfile); } return rv; } static int asepcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r, ftype, atype; sc_apdu_t apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE]; /* use GET DATA to determine whether it is a DF or EF */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x84); apdu.le = 256; apdu.resplen = sizeof(buf); apdu.resp = buf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { /* looks like a EF */ atype = SC_APDU_CASE_3_SHORT; ftype = 0x02; buf[0] = path->value[path->len-2]; buf[1] = path->value[path->len-1]; } else { /* presumably a DF */ atype = SC_APDU_CASE_1; ftype = 0x00; } sc_format_apdu(card, &apdu, atype, 0xe4, ftype, 0x00); if (atype == SC_APDU_CASE_3_SHORT) { apdu.lc = 2; apdu.datalen = 2; apdu.data = buf; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } /* returns the default transport key (note: this should be put in the * pkcs15 profile file). */ static int asepcos_get_default_key(sc_card_t *card, struct sc_cardctl_default_key *data) { static const u8 asepcos_def_key[] = {0x41,0x53,0x45,0x43,0x41,0x52,0x44,0x2b}; if (data->method != SC_AC_CHV && data->method != SC_AC_AUT) return SC_ERROR_NO_DEFAULT_KEY; if (data->key_data == NULL || data->len < sizeof(asepcos_def_key)) return SC_ERROR_BUFFER_TOO_SMALL; memcpy(data->key_data, asepcos_def_key, sizeof(asepcos_def_key)); data->len = sizeof(asepcos_def_key); return SC_SUCCESS; } static int asepcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x14); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (apdu.resplen != 8) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unexpected response to GET DATA serial number\n"); return SC_ERROR_INTERNAL; } /* cache serial number */ memcpy(card->serialnr.value, rbuf, 8); card->serialnr.len = 8; /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int asepcos_change_key(sc_card_t *card, sc_cardctl_asepcos_change_key_t *p) { int r, atype; sc_apdu_t apdu; if (p->datalen > 255) atype = SC_APDU_CASE_3_EXT; else atype = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, atype, 0x24, 0x01, 0x80); apdu.lc = p->datalen; apdu.datalen = p->datalen; apdu.data = p->data; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int asepcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_GET_DEFAULT_KEY: return asepcos_get_default_key(card, (struct sc_cardctl_default_key *) ptr); case SC_CARDCTL_GET_SERIALNR: return asepcos_get_serialnr(card, (sc_serial_number_t *)ptr); case SC_CARDCTL_ASEPCOS_CHANGE_KEY: return asepcos_change_key(card, (sc_cardctl_asepcos_change_key_t*)ptr); case SC_CARDCTL_ASEPCOS_AKN2FILEID: return asepcos_akn_to_fileid(card, (sc_cardctl_asepcos_akn2fileid_t*)ptr); case SC_CARDCTL_ASEPCOS_SET_SATTR: return asepcos_set_security_attributes(card, (sc_file_t*)ptr); case SC_CARDCTL_ASEPCOS_ACTIVATE_FILE: return asepcos_activate_file(card, ((sc_cardctl_asepcos_activate_file_t*)ptr)->fileid, ((sc_cardctl_asepcos_activate_file_t *)ptr)->is_ef); } return SC_ERROR_NOT_SUPPORTED; } /* build the different APDUs for the PIN handling commands */ static int asepcos_build_pin_apdu(sc_card_t *card, sc_apdu_t *apdu, struct sc_pin_cmd_data *data, u8 *buf, size_t buf_len, unsigned int cmd, int is_puk) { int r, fileid; u8 *p = buf; sc_cardctl_asepcos_akn2fileid_t st; switch (cmd) { case SC_PIN_CMD_VERIFY: st.akn = data->pin_reference; r = asepcos_akn_to_fileid(card, &st); if (r != SC_SUCCESS) return r; fileid = st.fileid; /* the fileid of the puk is the fileid of the pin + 1 */ if (is_puk != 0) fileid++; sc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x20, 0x02, 0x80); *p++ = (fileid >> 24) & 0xff; *p++ = (fileid >> 16) & 0xff; *p++ = (fileid >> 8 ) & 0xff; *p++ = fileid & 0xff; memcpy(p, data->pin1.data, data->pin1.len); p += data->pin1.len; apdu->lc = p - buf; apdu->datalen = p - buf; apdu->data = buf; break; case SC_PIN_CMD_CHANGE: /* build the CHANGE KEY apdu. Note: the PIN file is implicitly * selected by its SFID */ *p++ = 0x81; *p++ = data->pin2.len & 0xff; memcpy(p, data->pin2.data, data->pin2.len); p += data->pin2.len; st.akn = data->pin_reference; r = asepcos_akn_to_fileid(card, &st); if (r != SC_SUCCESS) return r; fileid = 0x80 | (st.fileid & 0x1f); sc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x01, fileid); apdu->lc = p - buf; apdu->datalen = p - buf; apdu->data = buf; break; case SC_PIN_CMD_UNBLOCK: /* build the UNBLOCK KEY apdu. The PIN file is implicitly * selected by its SFID. The new PIN is provided in the * data field of the UNBLOCK KEY command. */ *p++ = 0x81; *p++ = data->pin2.len & 0xff; memcpy(p, data->pin2.data, data->pin2.len); p += data->pin2.len; st.akn = data->pin_reference; r = asepcos_akn_to_fileid(card, &st); if (r != SC_SUCCESS) return r; fileid = 0x80 | (st.fileid & 0x1f); sc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, fileid); apdu->lc = p - buf; apdu->datalen = p - buf; apdu->data = buf; break; default: return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } /* generic function to handle the different PIN operations, i.e verify * change and unblock. */ static int asepcos_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *pdata, int *tries_left) { sc_apdu_t apdu; int r = SC_SUCCESS; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; if (tries_left) *tries_left = -1; /* only PIN verification is supported at the moment */ /* check PIN length */ if (pdata->pin1.len < 4 || pdata->pin1.len > 16) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid PIN1 length"); return SC_ERROR_INVALID_PIN_LENGTH; } switch (pdata->cmd) { case SC_PIN_CMD_VERIFY: if (pdata->pin_type != SC_AC_CHV && pdata->pin_type != SC_AC_AUT) return SC_ERROR_INVALID_ARGUMENTS; /* 'AUT' key is the transport PIN and should have reference '0' */ if (pdata->pin_type == SC_AC_AUT && pdata->pin_reference) return SC_ERROR_INVALID_ARGUMENTS; /* build verify APDU and send it to the card */ r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_VERIFY, 0); if (r != SC_SUCCESS) break; r = sc_transmit_apdu(card, &apdu); if (r != SC_SUCCESS) sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed"); break; case SC_PIN_CMD_CHANGE: if (pdata->pin_type != SC_AC_CHV) return SC_ERROR_INVALID_ARGUMENTS; if (pdata->pin2.len < 4 || pdata->pin2.len > 16) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid PIN2 length"); return SC_ERROR_INVALID_PIN_LENGTH; } /* 1. step: verify the old pin */ r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_VERIFY, 0); if (r != SC_SUCCESS) break; r = sc_transmit_apdu(card, &apdu); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed"); break; } if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) { /* unable to verify the old PIN */ break; } /* 2, step: use CHANGE KEY to update the PIN */ r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_CHANGE, 0); if (r != SC_SUCCESS) break; r = sc_transmit_apdu(card, &apdu); if (r != SC_SUCCESS) sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed"); break; case SC_PIN_CMD_UNBLOCK: if (pdata->pin_type != SC_AC_CHV) return SC_ERROR_INVALID_ARGUMENTS; if (pdata->pin2.len < 4 || pdata->pin2.len > 16) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid PIN2 length"); return SC_ERROR_INVALID_PIN_LENGTH; } /* 1. step: verify the puk */ r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_VERIFY, 1); if (r != SC_SUCCESS) break; r = sc_transmit_apdu(card, &apdu); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed"); break; } /* 2, step: unblock and change the pin */ r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_UNBLOCK, 0); if (r != SC_SUCCESS) break; r = sc_transmit_apdu(card, &apdu); if (r != SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed"); break; } break; default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "error: unknown cmd type"); return SC_ERROR_INTERNAL; } /* Clear the buffer - it may contain pins */ sc_mem_clear(sbuf, sizeof(sbuf)); /* check for remaining tries if verification failed */ if (r == SC_SUCCESS) { if (apdu.sw1 == 0x63) { if ((apdu.sw2 & 0xF0) == 0xC0 && tries_left != NULL) *tries_left = apdu.sw2 & 0x0F; r = SC_ERROR_PIN_CODE_INCORRECT; return r; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); } return r; } static int asepcos_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 && card->type == SC_CARD_TYPE_ASEPCOS_JAVA) { /* in case of a Java card try to select the ASEPCOS applet */ r = asepcos_select_asepcos_applet(card); } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { if (iso_ops == NULL) iso_ops = sc_get_iso7816_driver()->ops; asepcos_ops = *iso_ops; asepcos_ops.match_card = asepcos_match_card; asepcos_ops.init = asepcos_init; asepcos_ops.select_file = asepcos_select_file; asepcos_ops.set_security_env = asepcos_set_security_env; asepcos_ops.decipher = asepcos_decipher; asepcos_ops.compute_signature = asepcos_compute_signature; asepcos_ops.create_file = asepcos_create_file; asepcos_ops.delete_file = asepcos_delete_file; asepcos_ops.list_files = asepcos_list_files; asepcos_ops.card_ctl = asepcos_card_ctl; asepcos_ops.pin_cmd = asepcos_pin_cmd; asepcos_ops.card_reader_lock_obtained = asepcos_card_reader_lock_obtained; return &asepcos_drv; } struct sc_card_driver * sc_get_asepcos_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_1
crossvul-cpp_data_good_2731_0
/* * Copyright (c) 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Original code by Matt Thomas, Digital Equipment Corporation * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete IS-IS & CLNP support. */ /* \summary: ISO CLNS, ESIS, and ISIS printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "ether.h" #include "nlpid.h" #include "extract.h" #include "gmpls.h" #include "oui.h" #include "signature.h" static const char tstr[] = " [|isis]"; /* * IS-IS is defined in ISO 10589. Look there for protocol definitions. */ #define SYSTEM_ID_LEN ETHER_ADDR_LEN #define NODE_ID_LEN SYSTEM_ID_LEN+1 #define LSP_ID_LEN SYSTEM_ID_LEN+2 #define ISIS_VERSION 1 #define ESIS_VERSION 1 #define CLNP_VERSION 1 #define ISIS_PDU_TYPE_MASK 0x1F #define ESIS_PDU_TYPE_MASK 0x1F #define CLNP_PDU_TYPE_MASK 0x1F #define CLNP_FLAG_MASK 0xE0 #define ISIS_LAN_PRIORITY_MASK 0x7F #define ISIS_PDU_L1_LAN_IIH 15 #define ISIS_PDU_L2_LAN_IIH 16 #define ISIS_PDU_PTP_IIH 17 #define ISIS_PDU_L1_LSP 18 #define ISIS_PDU_L2_LSP 20 #define ISIS_PDU_L1_CSNP 24 #define ISIS_PDU_L2_CSNP 25 #define ISIS_PDU_L1_PSNP 26 #define ISIS_PDU_L2_PSNP 27 static const struct tok isis_pdu_values[] = { { ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"}, { ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"}, { ISIS_PDU_PTP_IIH, "p2p IIH"}, { ISIS_PDU_L1_LSP, "L1 LSP"}, { ISIS_PDU_L2_LSP, "L2 LSP"}, { ISIS_PDU_L1_CSNP, "L1 CSNP"}, { ISIS_PDU_L2_CSNP, "L2 CSNP"}, { ISIS_PDU_L1_PSNP, "L1 PSNP"}, { ISIS_PDU_L2_PSNP, "L2 PSNP"}, { 0, NULL} }; /* * A TLV is a tuple of a type, length and a value and is normally used for * encoding information in all sorts of places. This is an enumeration of * the well known types. * * list taken from rfc3359 plus some memory from veterans ;-) */ #define ISIS_TLV_AREA_ADDR 1 /* iso10589 */ #define ISIS_TLV_IS_REACH 2 /* iso10589 */ #define ISIS_TLV_ESNEIGH 3 /* iso10589 */ #define ISIS_TLV_PART_DIS 4 /* iso10589 */ #define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */ #define ISIS_TLV_ISNEIGH 6 /* iso10589 */ #define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */ #define ISIS_TLV_PADDING 8 /* iso10589 */ #define ISIS_TLV_LSP 9 /* iso10589 */ #define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */ #define ISIS_TLV_CHECKSUM 12 /* rfc3358 */ #define ISIS_TLV_CHECKSUM_MINLEN 2 #define ISIS_TLV_POI 13 /* rfc6232 */ #define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */ #define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2 #define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */ #define ISIS_TLV_DECNET_PHASE4 42 #define ISIS_TLV_LUCENT_PRIVATE 66 #define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */ #define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */ #define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */ #define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */ #define ISIS_TLV_IDRP_INFO_MINLEN 1 #define ISIS_TLV_IPADDR 132 /* rfc1195 */ #define ISIS_TLV_IPAUTH 133 /* rfc1195 */ #define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */ #define ISIS_TLV_HOSTNAME 137 /* rfc2763 */ #define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */ #define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */ #define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */ #define ISIS_TLV_NORTEL_PRIVATE1 176 #define ISIS_TLV_NORTEL_PRIVATE2 177 #define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */ #define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1 #define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2 #define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_MT_SUPPORTED_MINLEN 2 #define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */ #define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */ #define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */ #define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */ #define ISIS_TLV_IIH_SEQNR_MINLEN 4 #define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */ #define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3 static const struct tok isis_tlv_values[] = { { ISIS_TLV_AREA_ADDR, "Area address(es)"}, { ISIS_TLV_IS_REACH, "IS Reachability"}, { ISIS_TLV_ESNEIGH, "ES Neighbor(s)"}, { ISIS_TLV_PART_DIS, "Partition DIS"}, { ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"}, { ISIS_TLV_ISNEIGH, "IS Neighbor(s)"}, { ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"}, { ISIS_TLV_PADDING, "Padding"}, { ISIS_TLV_LSP, "LSP entries"}, { ISIS_TLV_AUTH, "Authentication"}, { ISIS_TLV_CHECKSUM, "Checksum"}, { ISIS_TLV_POI, "Purge Originator Identifier"}, { ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"}, { ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"}, { ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"}, { ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"}, { ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"}, { ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"}, { ISIS_TLV_PROTOCOLS, "Protocols supported"}, { ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"}, { ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"}, { ISIS_TLV_IPADDR, "IPv4 Interface address(es)"}, { ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"}, { ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"}, { ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"}, { ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"}, { ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"}, { ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"}, { ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"}, { ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"}, { ISIS_TLV_HOSTNAME, "Hostname"}, { ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"}, { ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"}, { ISIS_TLV_MT_SUPPORTED, "Multi Topology"}, { ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"}, { ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"}, { ISIS_TLV_IP6_REACH, "IPv6 reachability"}, { ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"}, { ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"}, { ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"}, { ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"}, { 0, NULL } }; #define ESIS_OPTION_PROTOCOLS 129 #define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */ #define ESIS_OPTION_SECURITY 197 /* iso9542 */ #define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */ #define ESIS_OPTION_PRIORITY 205 /* iso9542 */ #define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */ #define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */ static const struct tok esis_option_values[] = { { ESIS_OPTION_PROTOCOLS, "Protocols supported"}, { ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" }, { ESIS_OPTION_SECURITY, "Security" }, { ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" }, { ESIS_OPTION_PRIORITY, "Priority" }, { ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" }, { ESIS_OPTION_SNPA_MASK, "SNPA Mask" }, { 0, NULL } }; #define CLNP_OPTION_DISCARD_REASON 193 #define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */ #define CLNP_OPTION_SECURITY 197 /* iso8473 */ #define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */ #define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */ #define CLNP_OPTION_PADDING 204 /* iso8473 */ #define CLNP_OPTION_PRIORITY 205 /* iso8473 */ static const struct tok clnp_option_values[] = { { CLNP_OPTION_DISCARD_REASON, "Discard Reason"}, { CLNP_OPTION_PRIORITY, "Priority"}, { CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"}, { CLNP_OPTION_SECURITY, "Security"}, { CLNP_OPTION_SOURCE_ROUTING, "Source Routing"}, { CLNP_OPTION_ROUTE_RECORDING, "Route Recording"}, { CLNP_OPTION_PADDING, "Padding"}, { 0, NULL } }; static const struct tok clnp_option_rfd_class_values[] = { { 0x0, "General"}, { 0x8, "Address"}, { 0x9, "Source Routeing"}, { 0xa, "Lifetime"}, { 0xb, "PDU Discarded"}, { 0xc, "Reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_general_values[] = { { 0x0, "Reason not specified"}, { 0x1, "Protocol procedure error"}, { 0x2, "Incorrect checksum"}, { 0x3, "PDU discarded due to congestion"}, { 0x4, "Header syntax error (cannot be parsed)"}, { 0x5, "Segmentation needed but not permitted"}, { 0x6, "Incomplete PDU received"}, { 0x7, "Duplicate option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_address_values[] = { { 0x0, "Destination address unreachable"}, { 0x1, "Destination address unknown"}, { 0, NULL } }; static const struct tok clnp_option_rfd_source_routeing_values[] = { { 0x0, "Unspecified source routeing error"}, { 0x1, "Syntax error in source routeing field"}, { 0x2, "Unknown address in source routeing field"}, { 0x3, "Path not acceptable"}, { 0, NULL } }; static const struct tok clnp_option_rfd_lifetime_values[] = { { 0x0, "Lifetime expired while data unit in transit"}, { 0x1, "Lifetime expired during reassembly"}, { 0, NULL } }; static const struct tok clnp_option_rfd_pdu_discard_values[] = { { 0x0, "Unsupported option not specified"}, { 0x1, "Unsupported protocol version"}, { 0x2, "Unsupported security option"}, { 0x3, "Unsupported source routeing option"}, { 0x4, "Unsupported recording of route option"}, { 0, NULL } }; static const struct tok clnp_option_rfd_reassembly_values[] = { { 0x0, "Reassembly interference"}, { 0, NULL } }; /* array of 16 error-classes */ static const struct tok *clnp_option_rfd_error_class[] = { clnp_option_rfd_general_values, NULL, NULL, NULL, NULL, NULL, NULL, NULL, clnp_option_rfd_address_values, clnp_option_rfd_source_routeing_values, clnp_option_rfd_lifetime_values, clnp_option_rfd_pdu_discard_values, clnp_option_rfd_reassembly_values, NULL, NULL, NULL }; #define CLNP_OPTION_OPTION_QOS_MASK 0x3f #define CLNP_OPTION_SCOPE_MASK 0xc0 #define CLNP_OPTION_SCOPE_SA_SPEC 0x40 #define CLNP_OPTION_SCOPE_DA_SPEC 0x80 #define CLNP_OPTION_SCOPE_GLOBAL 0xc0 static const struct tok clnp_option_scope_values[] = { { CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"}, { CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"}, { CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_values[] = { { 0x0, "partial"}, { 0x1, "complete"}, { 0, NULL } }; static const struct tok clnp_option_sr_rr_string_values[] = { { CLNP_OPTION_SOURCE_ROUTING, "source routing"}, { CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"}, { 0, NULL } }; static const struct tok clnp_option_qos_global_values[] = { { 0x20, "reserved"}, { 0x10, "sequencing vs. delay"}, { 0x08, "congested"}, { 0x04, "delay vs. cost"}, { 0x02, "error vs. delay"}, { 0x01, "error vs. cost"}, { 0, NULL } }; #define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */ #define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */ #define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */ #define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */ #define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */ static const struct tok isis_ext_is_reach_subtlv_values[] = { { ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" }, { ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" }, { ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" }, { ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" }, { ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" }, { ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" }, { ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" }, { ISIS_SUBTLV_SPB_METRIC, "SPB Metric" }, { 250, "Reserved for cisco specific extensions" }, { 251, "Reserved for cisco specific extensions" }, { 252, "Reserved for cisco specific extensions" }, { 253, "Reserved for cisco specific extensions" }, { 254, "Reserved for cisco specific extensions" }, { 255, "Reserved for future expansion" }, { 0, NULL } }; #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */ #define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */ static const struct tok isis_ext_ip_reach_subtlv_values[] = { { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" }, { ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" }, { 0, NULL } }; static const struct tok isis_subtlv_link_attribute_values[] = { { 0x01, "Local Protection Available" }, { 0x02, "Link excluded from local protection path" }, { 0x04, "Local maintenance required"}, { 0, NULL } }; #define ISIS_SUBTLV_AUTH_SIMPLE 1 #define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */ #define ISIS_SUBTLV_AUTH_MD5 54 #define ISIS_SUBTLV_AUTH_MD5_LEN 16 #define ISIS_SUBTLV_AUTH_PRIVATE 255 static const struct tok isis_subtlv_auth_values[] = { { ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"}, { ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"}, { ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"}, { ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"}, { 0, NULL } }; #define ISIS_SUBTLV_IDRP_RES 0 #define ISIS_SUBTLV_IDRP_LOCAL 1 #define ISIS_SUBTLV_IDRP_ASN 2 static const struct tok isis_subtlv_idrp_values[] = { { ISIS_SUBTLV_IDRP_RES, "Reserved"}, { ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"}, { ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"}, { 0, NULL} }; #define ISIS_SUBTLV_SPB_MCID 4 #define ISIS_SUBTLV_SPB_DIGEST 5 #define ISIS_SUBTLV_SPB_BVID 6 #define ISIS_SUBTLV_SPB_INSTANCE 1 #define ISIS_SUBTLV_SPBM_SI 3 #define ISIS_SPB_MCID_LEN 51 #define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102 #define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33 #define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6 #define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19 #define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8 static const struct tok isis_mt_port_cap_subtlv_values[] = { { ISIS_SUBTLV_SPB_MCID, "SPB MCID" }, { ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" }, { ISIS_SUBTLV_SPB_BVID, "SPB BVID" }, { 0, NULL } }; static const struct tok isis_mt_capability_subtlv_values[] = { { ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" }, { ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" }, { 0, NULL } }; struct isis_spb_mcid { uint8_t format_id; uint8_t name[32]; uint8_t revision_lvl[2]; uint8_t digest[16]; }; struct isis_subtlv_spb_mcid { struct isis_spb_mcid mcid; struct isis_spb_mcid aux_mcid; }; struct isis_subtlv_spb_instance { uint8_t cist_root_id[8]; uint8_t cist_external_root_path_cost[4]; uint8_t bridge_priority[2]; uint8_t spsourceid[4]; uint8_t no_of_trees; }; #define CLNP_SEGMENT_PART 0x80 #define CLNP_MORE_SEGMENTS 0x40 #define CLNP_REQUEST_ER 0x20 static const struct tok clnp_flag_values[] = { { CLNP_SEGMENT_PART, "Segmentation permitted"}, { CLNP_MORE_SEGMENTS, "more Segments"}, { CLNP_REQUEST_ER, "request Error Report"}, { 0, NULL} }; #define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4) #define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3) #define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80) #define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78) #define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40) #define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20) #define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10) #define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8) #define ISIS_MASK_MTID(x) ((x)&0x0fff) #define ISIS_MASK_MTFLAGS(x) ((x)&0xf000) static const struct tok isis_mt_flag_values[] = { { 0x4000, "ATT bit set"}, { 0x8000, "Overload bit set"}, { 0, NULL} }; #define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80) #define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40) #define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20) #define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40) #define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80) #define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f) #define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1) static const struct tok isis_mt_values[] = { { 0, "IPv4 unicast"}, { 1, "In-Band Management"}, { 2, "IPv6 unicast"}, { 3, "Multicast"}, { 4095, "Development, Experimental or Proprietary"}, { 0, NULL } }; static const struct tok isis_iih_circuit_type_values[] = { { 1, "Level 1 only"}, { 2, "Level 2 only"}, { 3, "Level 1, Level 2"}, { 0, NULL} }; #define ISIS_LSP_TYPE_UNUSED0 0 #define ISIS_LSP_TYPE_LEVEL_1 1 #define ISIS_LSP_TYPE_UNUSED2 2 #define ISIS_LSP_TYPE_LEVEL_2 3 static const struct tok isis_lsp_istype_values[] = { { ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_1, "L1 IS"}, { ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"}, { ISIS_LSP_TYPE_LEVEL_2, "L2 IS"}, { 0, NULL } }; /* * Katz's point to point adjacency TLV uses codes to tell us the state of * the remote adjacency. Enumerate them. */ #define ISIS_PTP_ADJ_UP 0 #define ISIS_PTP_ADJ_INIT 1 #define ISIS_PTP_ADJ_DOWN 2 static const struct tok isis_ptp_adjancey_values[] = { { ISIS_PTP_ADJ_UP, "Up" }, { ISIS_PTP_ADJ_INIT, "Initializing" }, { ISIS_PTP_ADJ_DOWN, "Down" }, { 0, NULL} }; struct isis_tlv_ptp_adj { uint8_t adjacency_state; uint8_t extd_local_circuit_id[4]; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; uint8_t neighbor_extd_local_circuit_id[4]; }; static void osi_print_cksum(netdissect_options *, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length); static int clnp_print(netdissect_options *, const uint8_t *, u_int); static void esis_print(netdissect_options *, const uint8_t *, u_int); static int isis_print(netdissect_options *, const uint8_t *, u_int); struct isis_metric_block { uint8_t metric_default; uint8_t metric_delay; uint8_t metric_expense; uint8_t metric_error; }; struct isis_tlv_is_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_nodeid[NODE_ID_LEN]; }; struct isis_tlv_es_reach { struct isis_metric_block isis_metric_block; uint8_t neighbor_sysid[SYSTEM_ID_LEN]; }; struct isis_tlv_ip_reach { struct isis_metric_block isis_metric_block; uint8_t prefix[4]; uint8_t mask[4]; }; static const struct tok isis_is_reach_virtual_values[] = { { 0, "IsNotVirtual"}, { 1, "IsVirtual"}, { 0, NULL } }; static const struct tok isis_restart_flag_values[] = { { 0x1, "Restart Request"}, { 0x2, "Restart Acknowledgement"}, { 0x4, "Suppress adjacency advertisement"}, { 0, NULL } }; struct isis_common_header { uint8_t nlpid; uint8_t fixed_len; uint8_t version; /* Protocol version */ uint8_t id_length; uint8_t pdu_type; /* 3 MSbits are reserved */ uint8_t pdu_version; /* Packet format version */ uint8_t reserved; uint8_t max_area; }; struct isis_iih_lan_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t priority; uint8_t lan_id[NODE_ID_LEN]; }; struct isis_iih_ptp_header { uint8_t circuit_type; uint8_t source_id[SYSTEM_ID_LEN]; uint8_t holding_time[2]; uint8_t pdu_len[2]; uint8_t circuit_id; }; struct isis_lsp_header { uint8_t pdu_len[2]; uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; uint8_t typeblock; }; struct isis_csnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; uint8_t start_lsp_id[LSP_ID_LEN]; uint8_t end_lsp_id[LSP_ID_LEN]; }; struct isis_psnp_header { uint8_t pdu_len[2]; uint8_t source_id[NODE_ID_LEN]; }; struct isis_tlv_lsp { uint8_t remaining_lifetime[2]; uint8_t lsp_id[LSP_ID_LEN]; uint8_t sequence_number[4]; uint8_t checksum[2]; }; #define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header)) #define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header)) #define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header)) #define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header)) #define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header)) #define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header)) void isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length) { if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */ ND_PRINT((ndo, "|OSI")); return; } if (ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p)); switch (*p) { case NLPID_CLNP: if (!clnp_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_ESIS: esis_print(ndo, p, length); return; case NLPID_ISIS: if (!isis_print(ndo, p, length)) print_unknown_data(ndo, p, "\n\t", length); break; case NLPID_NULLNS: ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); break; case NLPID_Q933: q933_print(ndo, p + 1, length - 1); break; case NLPID_IP: ip_print(ndo, p + 1, length - 1); break; case NLPID_IP6: ip6_print(ndo, p + 1, length - 1); break; case NLPID_PPP: ppp_print(ndo, p + 1, length - 1); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p)); ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length)); if (length > 1) print_unknown_data(ndo, p, "\n\t", length); break; } } #define CLNP_PDU_ER 1 #define CLNP_PDU_DT 28 #define CLNP_PDU_MD 29 #define CLNP_PDU_ERQ 30 #define CLNP_PDU_ERP 31 static const struct tok clnp_pdu_values[] = { { CLNP_PDU_ER, "Error Report"}, { CLNP_PDU_MD, "MD"}, { CLNP_PDU_DT, "Data"}, { CLNP_PDU_ERQ, "Echo Request"}, { CLNP_PDU_ERP, "Echo Response"}, { 0, NULL } }; struct clnp_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t lifetime; /* units of 500ms */ uint8_t type; uint8_t segment_length[2]; uint8_t cksum[2]; }; struct clnp_segment_header_t { uint8_t data_unit_id[2]; uint8_t segment_offset[2]; uint8_t total_length[2]; }; /* * clnp_print * Decode CLNP packets. Return 0 on error. */ static int clnp_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr,*source_address,*dest_address; u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags; const struct clnp_header_t *clnp_header; const struct clnp_segment_header_t *clnp_segment_header; uint8_t rfd_error_major,rfd_error_minor; clnp_header = (const struct clnp_header_t *) pptr; ND_TCHECK(*clnp_header); li = clnp_header->length_indicator; optr = pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "CLNP")); /* * Sanity checking of the header. */ if (clnp_header->version != CLNP_VERSION) { ND_PRINT((ndo, "version %d packet not supported", clnp_header->version)); return (0); } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return (0); } if (li < sizeof(struct clnp_header_t)) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return (0); } /* FIXME further header sanity checking */ clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK; clnp_flags = clnp_header->type & CLNP_FLAG_MASK; pptr += sizeof(struct clnp_header_t); li -= sizeof(struct clnp_header_t); if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); dest_address_length = *pptr; pptr += 1; li -= 1; if (li < dest_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, dest_address_length); dest_address = pptr; pptr += dest_address_length; li -= dest_address_length; if (li < 1) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK(*pptr); source_address_length = *pptr; pptr += 1; li -= 1; if (li < source_address_length) { ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses")); return (0); } ND_TCHECK2(*pptr, source_address_length); source_address = pptr; pptr += source_address_length; li -= source_address_length; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s > %s, %s, length %u", ndo->ndo_eflag ? "" : ", ", isonsap_string(ndo, source_address, source_address_length), isonsap_string(ndo, dest_address, dest_address_length), tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type), length)); return (1); } ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x", tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type), clnp_header->length_indicator, clnp_header->version, clnp_header->lifetime/2, (clnp_header->lifetime%2)*5, EXTRACT_16BITS(clnp_header->segment_length), EXTRACT_16BITS(clnp_header->cksum))); osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7, clnp_header->length_indicator); ND_PRINT((ndo, "\n\tFlags [%s]", bittok2str(clnp_flag_values, "none", clnp_flags))); ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length), dest_address_length, isonsap_string(ndo, dest_address, dest_address_length))); if (clnp_flags & CLNP_SEGMENT_PART) { if (li < sizeof(const struct clnp_segment_header_t)) { ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part")); return (0); } clnp_segment_header = (const struct clnp_segment_header_t *) pptr; ND_TCHECK(*clnp_segment_header); ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u", EXTRACT_16BITS(clnp_segment_header->data_unit_id), EXTRACT_16BITS(clnp_segment_header->segment_offset), EXTRACT_16BITS(clnp_segment_header->total_length))); pptr+=sizeof(const struct clnp_segment_header_t); li-=sizeof(const struct clnp_segment_header_t); } /* now walk the options */ while (li >= 2) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return (0); } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return (0); } ND_TCHECK2(*pptr, opli); li -= opli; tptr = pptr; tlen = opli; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(clnp_option_values,"Unknown",op), op, opli)); /* * We've already checked that the entire option is present * in the captured packet with the ND_TCHECK2() call. * Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2() * checks. * We do, however, need to check tlen, to make sure we * don't run past the end of the option. */ switch (op) { case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */ case CLNP_OPTION_SOURCE_ROUTING: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "%s %s", tok2str(clnp_option_sr_rr_values,"Unknown",*tptr), tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op))); nsap_offset=*(tptr+1); if (nsap_offset == 0) { ND_PRINT((ndo, " Bad NSAP offset (0)")); break; } nsap_offset-=1; /* offset to nsap list */ if (nsap_offset > tlen) { ND_PRINT((ndo, " Bad NSAP offset (past end of option)")); break; } tptr+=nsap_offset; tlen-=nsap_offset; while (tlen > 0) { source_address_length=*tptr; if (tlen < source_address_length+1) { ND_PRINT((ndo, "\n\t NSAP address goes past end of option")); break; } if (source_address_length > 0) { source_address=(tptr+1); ND_TCHECK2(*source_address, source_address_length); ND_PRINT((ndo, "\n\t NSAP address (length %u): %s", source_address_length, isonsap_string(ndo, source_address, source_address_length))); } tlen-=source_address_length+1; } break; case CLNP_OPTION_PRIORITY: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "0x%1x", *tptr&0x0f)); break; case CLNP_OPTION_QOS_MAINTENANCE: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s", tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK))); if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL) ND_PRINT((ndo, "\n\t QoS Flags [%s]", bittok2str(clnp_option_qos_global_values, "none", *tptr&CLNP_OPTION_OPTION_QOS_MASK))); break; case CLNP_OPTION_SECURITY: if (tlen < 2) { ND_PRINT((ndo, ", bad opt len")); return (0); } ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u", tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK), *(tptr+1))); break; case CLNP_OPTION_DISCARD_REASON: if (tlen < 1) { ND_PRINT((ndo, ", bad opt len")); return (0); } rfd_error_major = (*tptr&0xf0) >> 4; rfd_error_minor = *tptr&0x0f; ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)", tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major), rfd_error_major, tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor), rfd_error_minor)); break; case CLNP_OPTION_PADDING: ND_PRINT((ndo, "padding data")); break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } switch (clnp_pdu_type) { case CLNP_PDU_ER: /* fall through */ case CLNP_PDU_ERP: ND_TCHECK(*pptr); if (*(pptr) == NLPID_CLNP) { ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); /* FIXME recursion protection */ clnp_print(ndo, pptr, length - clnp_header->length_indicator); break; } case CLNP_PDU_DT: case CLNP_PDU_MD: case CLNP_PDU_ERQ: default: /* dump the PDU specific data */ if (length-(pptr-optr) > 0) { ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator)); print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr)); } } return (1); trunc: ND_PRINT((ndo, "[|clnp]")); return (1); } #define ESIS_PDU_REDIRECT 6 #define ESIS_PDU_ESH 2 #define ESIS_PDU_ISH 4 static const struct tok esis_pdu_values[] = { { ESIS_PDU_REDIRECT, "redirect"}, { ESIS_PDU_ESH, "ESH"}, { ESIS_PDU_ISH, "ISH"}, { 0, NULL } }; struct esis_header_t { uint8_t nlpid; uint8_t length_indicator; uint8_t version; uint8_t reserved; uint8_t type; uint8_t holdtime[2]; uint8_t cksum[2]; }; static void esis_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr; u_int li,esis_pdu_type,source_address_length, source_address_number; const struct esis_header_t *esis_header; if (!ndo->ndo_eflag) ND_PRINT((ndo, "ES-IS")); if (length <= 2) { ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!")); return; } esis_header = (const struct esis_header_t *) pptr; ND_TCHECK(*esis_header); li = esis_header->length_indicator; optr = pptr; /* * Sanity checking of the header. */ if (esis_header->nlpid != NLPID_ESIS) { ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid)); return; } if (esis_header->version != ESIS_VERSION) { ND_PRINT((ndo, " version %d packet not supported", esis_header->version)); return; } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return; } if (li < sizeof(struct esis_header_t) + 2) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return; } esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s, length %u", ndo->ndo_eflag ? "" : ", ", tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type), length)); return; } else ND_PRINT((ndo, "%slength %u\n\t%s (%u)", ndo->ndo_eflag ? "" : ", ", length, tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type), esis_pdu_type)); ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" )); ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum))); osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li); ND_PRINT((ndo, ", holding time: %us, length indicator: %u", EXTRACT_16BITS(esis_header->holdtime), li)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t)); pptr += sizeof(struct esis_header_t); li -= sizeof(struct esis_header_t); switch (esis_pdu_type) { case ESIS_PDU_REDIRECT: { const uint8_t *dst, *snpa, *neta; u_int dstl, snpal, netal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } dstl = *pptr; pptr++; li--; ND_TCHECK2(*pptr, dstl); if (li < dstl) { ND_PRINT((ndo, ", bad redirect/li")); return; } dst = pptr; pptr += dstl; li -= dstl; ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl))); ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpal = *pptr; pptr++; li--; ND_TCHECK2(*pptr, snpal); if (li < snpal) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpa = pptr; pptr += snpal; li -= snpal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } netal = *pptr; pptr++; ND_TCHECK2(*pptr, netal); if (li < netal) { ND_PRINT((ndo, ", bad redirect/li")); return; } neta = pptr; pptr += netal; li -= netal; if (snpal == 6) ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, etheraddr_string(ndo, snpa))); else ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal))); if (netal != 0) ND_PRINT((ndo, "\n\t NET (length: %u) %s", netal, isonsap_string(ndo, neta, netal))); break; } case ESIS_PDU_ESH: ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_number = *pptr; pptr++; li--; ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number)); while (source_address_number > 0) { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad esh/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; source_address_number--; } break; case ESIS_PDU_ISH: { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad ish/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad ish/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; break; } default: if (ndo->ndo_vflag <= 1) { if (pptr < ndo->ndo_snapend) print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr); } return; } /* now walk the options */ while (li != 0) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return; } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return; } li -= opli; tptr = pptr; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(esis_option_values,"Unknown",op), op, opli)); switch (op) { case ESIS_OPTION_ES_CONF_TIME: if (opli == 2) { ND_TCHECK2(*pptr, 2); ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr))); } else ND_PRINT((ndo, "(bad length)")); break; case ESIS_OPTION_PROTOCOLS: while (opli>0) { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (opli>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; opli--; } break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ case ESIS_OPTION_QOS_MAINTENANCE: case ESIS_OPTION_SECURITY: case ESIS_OPTION_PRIORITY: case ESIS_OPTION_ADDRESS_MASK: case ESIS_OPTION_SNPA_MASK: default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } trunc: ND_PRINT((ndo, "[|esis]")); } static void isis_print_mcid(netdissect_options *ndo, const struct isis_spb_mcid *mcid) { int i; ND_TCHECK(*mcid); ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id)); if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend)) goto trunc; ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl))); ND_PRINT((ndo, ", Digest: ")); for(i=0;i<16;i++) ND_PRINT((ndo, "%.2x ", mcid->digest[i])); trunc: ND_PRINT((ndo, "%s", tstr)); } static int isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN) goto trunc; subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN; len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; break; } case ISIS_SUBTLV_SPB_DIGEST: { if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN) goto trunc; ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static int isis_print_mt_capability_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len, tmp; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); len = len - 2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_INSTANCE: if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN) goto trunc; ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr))); tptr = tptr + 2; ND_PRINT((ndo, "\n\t RES: %d", EXTRACT_16BITS(tptr) >> 5)); ND_PRINT((ndo, ", V: %d", (EXTRACT_16BITS(tptr) >> 4) & 0x0001)); ND_PRINT((ndo, ", SPSource-ID: %d", (EXTRACT_32BITS(tptr) & 0x000fffff))); tptr = tptr+4; ND_PRINT((ndo, ", No of Trees: %x", *(tptr))); tmp = *(tptr++); len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN; while (tmp) { if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN) goto trunc; ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d", *(tptr) >> 7, (*(tptr) >> 6) & 0x01, (*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f))); tptr++; ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr + 4; ND_PRINT((ndo, ", BVID: %d, SPVID: %d", (EXTRACT_24BITS(tptr) >> 12) & 0x000fff, EXTRACT_24BITS(tptr) & 0x000fff)); tptr = tptr + 3; len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN; tmp--; } break; case ISIS_SUBTLV_SPBM_SI: if (stlv_len < 8) goto trunc; ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr))); tptr = tptr+2; ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12, (EXTRACT_16BITS(tptr)) & 0x0fff)); tptr = tptr+2; len = len - 8; stlv_len = stlv_len - 8; while (stlv_len >= 4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d", (EXTRACT_32BITS(tptr) >> 31), (EXTRACT_32BITS(tptr) >> 30) & 0x01, (EXTRACT_32BITS(tptr) >> 24) & 0x03f, (EXTRACT_32BITS(tptr)) & 0x0ffffff)); tptr = tptr + 4; len = len - 4; stlv_len = stlv_len - 4; } break; default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } /* shared routine for printing system, node and lsp-ids */ static char * isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; int sysid_len; sysid_len = SYSTEM_ID_LEN; if (sysid_len > id_len) sysid_len = id_len; for (i = 1; i <= sysid_len; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } /* print the 4-byte metric block which is common found in the old-style TLVs */ static int isis_print_metric_block(netdissect_options *ndo, const struct isis_metric_block *isis_metric_block) { ND_PRINT((ndo, ", Default Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay)) ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense)) ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error)) ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s", ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error), ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal")); return(1); /* everything is ok */ } static int isis_print_tlv_ip_reach(netdissect_options *ndo, const uint8_t *cp, const char *ident, int length) { int prefix_len; const struct isis_tlv_ip_reach *tlv_ip_reach; tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp; while (length > 0) { if ((size_t)length < sizeof(*tlv_ip_reach)) { ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)", length, (unsigned long)sizeof(*tlv_ip_reach))); return (0); } if (!ND_TTEST(*tlv_ip_reach)) return (0); prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask)); if (prefix_len == -1) ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), ipaddr_string(ndo, (tlv_ip_reach->mask)))); else ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, (tlv_ip_reach->prefix)), prefix_len)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s", ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up", ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay)) ND_PRINT((ndo, "%s Delay Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense)) ND_PRINT((ndo, "%s Expense Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal")); if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error)) ND_PRINT((ndo, "%s Error Metric: %u, %s", ident, ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error), ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal")); length -= sizeof(struct isis_tlv_ip_reach); tlv_ip_reach++; } return (1); } /* * this is the common IP-REACH subTLV decoder it is called * from various EXTD-IP REACH TLVs (135,235,236,237) */ static int isis_print_ip_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, int subt, int subl, const char *ident) { /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr,subl); switch(subt) { case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */ case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32: while (subl >= 4) { ND_PRINT((ndo, ", 0x%08x (=%u)", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr))); tptr+=4; subl-=4; } break; case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64: while (subl >= 8) { ND_PRINT((ndo, ", 0x%08x%08x", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr+4))); tptr+=8; subl-=8; } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: ND_PRINT((ndo, "%s", ident)); ND_PRINT((ndo, "%s", tstr)); return(0); } /* * this is the common IS-REACH subTLV decoder it is called * from isis_print_ext_is_reach() */ static int isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: if (subl == 0) break; ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } /* * this is the common IS-REACH decoder it is called * from various EXTD-IS REACH style TLVs (22,24,222) */ static int isis_print_ext_is_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, int tlv_type) { char ident_buffer[20]; int subtlv_type,subtlv_len,subtlv_sum_len; int proc_bytes = 0; /* how many bytes did we process ? */ if (!ND_TTEST2(*tptr, NODE_ID_LEN)) return(0); ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */ if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */ return(0); ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr))); tptr+=3; } if (!ND_TTEST2(*tptr, 1)) return(0); subtlv_sum_len=*(tptr++); /* read out subTLV length */ proc_bytes=NODE_ID_LEN+3+1; ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no ")); if (subtlv_sum_len) { ND_PRINT((ndo, " (%u)", subtlv_sum_len)); while (subtlv_sum_len>0) { if (!ND_TTEST2(*tptr,2)) return(0); subtlv_type=*(tptr++); subtlv_len=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer)) return(0); tptr+=subtlv_len; subtlv_sum_len-=(subtlv_len+2); proc_bytes+=(subtlv_len+2); } } return(proc_bytes); } /* * this is the common Multi Topology ID decoder * it is called from various MT-TLVs (222,229,235,237) */ static int isis_print_mtid(netdissect_options *ndo, const uint8_t *tptr, const char *ident) { if (!ND_TTEST2(*tptr, 2)) return(0); ND_PRINT((ndo, "%s%s", ident, tok2str(isis_mt_values, "Reserved for IETF Consensus", ISIS_MASK_MTID(EXTRACT_16BITS(tptr))))); ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]", ISIS_MASK_MTID(EXTRACT_16BITS(tptr)), bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr))))); return(2); } /* * this is the common extended IP reach decoder * it is called from TLVs (135,235,236,237) * we process the TLV and optional subTLVs and return * the amount of processed bytes */ static int isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } /* * Clear checksum and lifetime prior to signature verification. */ static void isis_clear_checksum_lifetime(void *header) { struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header; header_lsp->checksum[0] = 0; header_lsp->checksum[1] = 0; header_lsp->remaining_lifetime[0] = 0; header_lsp->remaining_lifetime[1] = 0; } /* * isis_print * Decode IS-IS packets. Return 0 on error. */ static int isis_print(netdissect_options *ndo, const uint8_t *p, u_int length) { const struct isis_common_header *isis_header; const struct isis_iih_lan_header *header_iih_lan; const struct isis_iih_ptp_header *header_iih_ptp; const struct isis_lsp_header *header_lsp; const struct isis_csnp_header *header_csnp; const struct isis_psnp_header *header_psnp; const struct isis_tlv_lsp *tlv_lsp; const struct isis_tlv_ptp_adj *tlv_ptp_adj; const struct isis_tlv_is_reach *tlv_is_reach; const struct isis_tlv_es_reach *tlv_es_reach; uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len; uint8_t ext_is_len, ext_ip_len, mt_len; const uint8_t *optr, *pptr, *tptr; u_short packet_len,pdu_len, key_id; u_int i,vendor_id; int sigcheck; packet_len=length; optr = p; /* initialize the _o_riginal pointer to the packet start - need it for parsing the checksum TLV and authentication TLV verification */ isis_header = (const struct isis_common_header *)p; ND_TCHECK(*isis_header); if (length < ISIS_COMMON_HEADER_SIZE) goto trunc; pptr = p+(ISIS_COMMON_HEADER_SIZE); header_iih_lan = (const struct isis_iih_lan_header *)pptr; header_iih_ptp = (const struct isis_iih_ptp_header *)pptr; header_lsp = (const struct isis_lsp_header *)pptr; header_csnp = (const struct isis_csnp_header *)pptr; header_psnp = (const struct isis_psnp_header *)pptr; if (!ndo->ndo_eflag) ND_PRINT((ndo, "IS-IS")); /* * Sanity checking of the header. */ if (isis_header->version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->version)); return (0); } if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) { ND_PRINT((ndo, "system ID length of %d is not supported", isis_header->id_length)); return (0); } if (isis_header->pdu_version != ISIS_VERSION) { ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version)); return (0); } if (length < isis_header->fixed_len) { ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length)); return (0); } if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) { ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE)); return (0); } max_area = isis_header->max_area; switch(max_area) { case 0: max_area = 3; /* silly shit */ break; case 255: ND_PRINT((ndo, "bad packet -- 255 areas")); return (0); default: break; } id_length = isis_header->id_length; switch(id_length) { case 0: id_length = 6; /* silly shit again */ break; case 1: /* 1-8 are valid sys-ID lenghts */ case 2: case 3: case 4: case 5: case 6: case 7: case 8: break; case 255: id_length = 0; /* entirely useless */ break; default: break; } /* toss any non 6-byte sys-ID len PDUs */ if (id_length != 6 ) { ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length)); return (0); } pdu_type=isis_header->pdu_type; /* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/ if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, "%s%s", ndo->ndo_eflag ? "" : ", ", tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type))); } else { /* ok they seem to want to know everything - lets fully decode it */ ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length)); ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)", tok2str(isis_pdu_values, "unknown, type %u", pdu_type), isis_header->fixed_len, isis_header->version, isis_header->pdu_version, id_length, isis_header->id_length, max_area, isis_header->max_area)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */ return (0); /* for optionally debugging the common header */ } } switch (pdu_type) { case ISIS_PDU_L1_LAN_IIH: case ISIS_PDU_L2_LAN_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_lan); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", lan-id %s, prio %u", isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN), header_iih_lan->priority)); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_lan->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_lan->circuit_type))); ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u", isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN), (header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); break; case ISIS_PDU_PTP_IIH: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_iih_ptp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]", isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN), EXTRACT_16BITS(header_iih_ptp->holding_time), tok2str(isis_iih_circuit_type_values, "unknown circuit type 0x%02x", header_iih_ptp->circuit_type))); ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u", header_iih_ptp->circuit_id, pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); break; case ISIS_PDU_L1_LSP: case ISIS_PDU_L2_LSP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE)); return (0); } ND_TCHECK(*header_lsp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_lsp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x", isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), EXTRACT_32BITS(header_lsp->sequence_number), EXTRACT_16BITS(header_lsp->remaining_lifetime), EXTRACT_16BITS(header_lsp->checksum))); osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id, EXTRACT_16BITS(header_lsp->checksum), 12, length-12); ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s", pdu_len, ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : "")); if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) { ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : "")); ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : "")); ND_PRINT((ndo, "ATT bit set, ")); } ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : "")); ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)", ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock)))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); break; case ISIS_PDU_L1_CSNP: case ISIS_PDU_L2_CSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) { ND_PRINT((ndo, ", bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_csnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_csnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_csnp->source_id, NODE_ID_LEN), pdu_len)); ND_PRINT((ndo, "\n\t start lsp-id: %s", isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN))); ND_PRINT((ndo, "\n\t end lsp-id: %s", isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN))); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); break; case ISIS_PDU_L1_PSNP: case ISIS_PDU_L2_PSNP: if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) { ND_PRINT((ndo, "- bogus fixed header length %u should be %lu", isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE))); return (0); } ND_TCHECK(*header_psnp); if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE) goto trunc; if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN))); ND_PRINT((ndo, ", length %u", length)); return (1); } pdu_len=EXTRACT_16BITS(header_psnp->pdu_len); if (packet_len>pdu_len) { packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ length=pdu_len; } ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u", isis_print_id(header_psnp->source_id, NODE_ID_LEN), pdu_len)); if (ndo->ndo_vflag > 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE)) return (0); } packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); break; default: if (ndo->ndo_vflag == 0) { ND_PRINT((ndo, ", length %u", length)); return (1); } (void)print_unknown_data(ndo, pptr, "\n\t ", length); return (0); } /* * Now print the TLV's. */ while (packet_len > 0) { ND_TCHECK2(*pptr, 2); if (packet_len < 2) goto trunc; tlv_type = *pptr++; tlv_len = *pptr++; tmp =tlv_len; /* copy temporary len & pointer to packet data */ tptr = pptr; packet_len -= 2; /* first lets see if we know the TLVs name*/ ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u", tok2str(isis_tlv_values, "unknown", tlv_type), tlv_type, tlv_len)); if (tlv_len == 0) /* something is invalid */ continue; if (packet_len < tlv_len) goto trunc; /* now check if we have a decoder otherwise do a hexdump at the end*/ switch (tlv_type) { case ISIS_TLV_AREA_ADDR: ND_TCHECK2(*tptr, 1); alen = *tptr++; while (tmp && alen < tmp) { ND_TCHECK2(*tptr, alen); ND_PRINT((ndo, "\n\t Area address (length: %u): %s", alen, isonsap_string(ndo, tptr, alen))); tptr += alen; tmp -= alen + 1; if (tmp==0) /* if this is the last area address do not attemt a boundary check */ break; ND_TCHECK2(*tptr, 1); alen = *tptr++; } break; case ISIS_TLV_ISNEIGH: while (tmp >= ETHER_ADDR_LEN) { ND_TCHECK2(*tptr, ETHER_ADDR_LEN); ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN))); tmp -= ETHER_ADDR_LEN; tptr += ETHER_ADDR_LEN; } break; case ISIS_TLV_ISNEIGH_VARLEN: if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */ goto trunctlv; lan_alen = *tptr++; /* LAN address length */ if (lan_alen == 0) { ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)")); break; } tmp --; ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen)); while (tmp >= lan_alen) { ND_TCHECK2(*tptr, lan_alen); ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen))); tmp -= lan_alen; tptr +=lan_alen; } break; case ISIS_TLV_PADDING: break; case ISIS_TLV_MT_IS_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; while (tmp >= 2+NODE_ID_LEN+3+1) { ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_ALIAS_ID: while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_EXT_IS_REACH: while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */ ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type); if (ext_is_len == 0) /* did something go wrong ? */ goto trunctlv; tmp-=ext_is_len; tptr+=ext_is_len; } break; case ISIS_TLV_IS_REACH: ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */ ND_PRINT((ndo, "\n\t %s", tok2str(isis_is_reach_virtual_values, "bogus virtual flag 0x%02x", *tptr++))); tlv_is_reach = (const struct isis_tlv_is_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_is_reach)) { ND_TCHECK(*tlv_is_reach); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN))); isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_is_reach); tlv_is_reach++; } break; case ISIS_TLV_ESNEIGH: tlv_es_reach = (const struct isis_tlv_es_reach *)tptr; while (tmp >= sizeof(struct isis_tlv_es_reach)) { ND_TCHECK(*tlv_es_reach); ND_PRINT((ndo, "\n\t ES Neighbor: %s", isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN))); isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block); tmp -= sizeof(struct isis_tlv_es_reach); tlv_es_reach++; } break; /* those two TLVs share the same format */ case ISIS_TLV_INT_IP_REACH: case ISIS_TLV_EXT_IP_REACH: if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len)) return (1); break; case ISIS_TLV_EXTD_IP_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6_REACH: while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_MT_IP6_REACH: mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) { /* did something go wrong ? */ goto trunctlv; } tptr+=mt_len; tmp-=mt_len; while (tmp>0) { ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6); if (ext_ip_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=ext_ip_len; tmp-=ext_ip_len; } break; case ISIS_TLV_IP6ADDR: while (tmp>=sizeof(struct in6_addr)) { ND_TCHECK2(*tptr, sizeof(struct in6_addr)); ND_PRINT((ndo, "\n\t IPv6 interface address: %s", ip6addr_string(ndo, tptr))); tptr += sizeof(struct in6_addr); tmp -= sizeof(struct in6_addr); } break; case ISIS_TLV_AUTH: ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t %s: ", tok2str(isis_subtlv_auth_values, "unknown Authentication type 0x%02x", *tptr))); switch (*tptr) { case ISIS_SUBTLV_AUTH_SIMPLE: if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_SUBTLV_AUTH_MD5: for(i=1;i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1) ND_PRINT((ndo, ", (invalid subTLV) ")); sigcheck = signature_verify(ndo, optr, length, tptr + 1, isis_clear_checksum_lifetime, header_lsp); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); break; case ISIS_SUBTLV_AUTH_GENERIC: ND_TCHECK2(*(tptr + 1), 2); key_id = EXTRACT_16BITS((tptr+1)); ND_PRINT((ndo, "%u, password: ", key_id)); for(i=1 + sizeof(uint16_t);i<tlv_len;i++) { ND_TCHECK2(*(tptr + i), 1); ND_PRINT((ndo, "%02x", *(tptr + i))); } break; case ISIS_SUBTLV_AUTH_PRIVATE: default: if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_PTP_ADJ: tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr; if(tmp>=1) { ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)", tok2str(isis_ptp_adjancey_values, "unknown", *tptr), *tptr)); tmp--; } if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id); ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id))); tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id); } if(tmp>=SYSTEM_ID_LEN) { ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t Neighbor System-ID: %s", isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN))); tmp-=SYSTEM_ID_LEN; } if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) { ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id); ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x", EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id))); } break; case ISIS_TLV_PROTOCOLS: ND_PRINT((ndo, "\n\t NLPID(s): ")); while (tmp>0) { ND_TCHECK2(*(tptr), 1); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (tmp>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; tmp--; } break; case ISIS_TLV_MT_PORT_CAP: { ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d", (EXTRACT_16BITS (tptr) >> 12), (EXTRACT_16BITS (tptr) & 0x0fff))); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_port_cap_subtlv(ndo, tptr, tmp); break; } case ISIS_TLV_MT_CAPABILITY: ND_TCHECK2(*(tptr), 2); ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d", (EXTRACT_16BITS(tptr) >> 15) & 0x01, (EXTRACT_16BITS(tptr) >> 12) & 0x07, EXTRACT_16BITS(tptr) & 0x0fff)); tmp = tmp-2; tptr = tptr+2; if (tmp) isis_print_mt_capability_subtlv(ndo, tptr, tmp); break; case ISIS_TLV_TE_ROUTER_ID: ND_TCHECK2(*pptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr))); break; case ISIS_TLV_IPADDR: while (tmp>=sizeof(struct in_addr)) { ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr += sizeof(struct in_addr); tmp -= sizeof(struct in_addr); } break; case ISIS_TLV_HOSTNAME: ND_PRINT((ndo, "\n\t Hostname: ")); if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend)) goto trunctlv; break; case ISIS_TLV_SHARED_RISK_GROUP: if (tmp < NODE_ID_LEN) break; ND_TCHECK2(*tptr, NODE_ID_LEN); ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN))); tptr+=(NODE_ID_LEN); tmp-=(NODE_ID_LEN); if (tmp < 1) break; ND_TCHECK2(*tptr, 1); ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered")); tmp--; if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); if (tmp < sizeof(struct in_addr)) break; ND_TCHECK2(*tptr, sizeof(struct in_addr)); ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr))); tptr+=sizeof(struct in_addr); tmp-=sizeof(struct in_addr); while (tmp>=4) { ND_TCHECK2(*tptr, 4); ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr))); tptr+=4; tmp-=4; } break; case ISIS_TLV_LSP: tlv_lsp = (const struct isis_tlv_lsp *)tptr; while(tmp>=sizeof(struct isis_tlv_lsp)) { ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]); ND_PRINT((ndo, "\n\t lsp-id: %s", isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN))); ND_TCHECK2(tlv_lsp->sequence_number, 4); ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number))); ND_TCHECK2(tlv_lsp->remaining_lifetime, 2); ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime))); ND_TCHECK2(tlv_lsp->checksum, 2); ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum))); tmp-=sizeof(struct isis_tlv_lsp); tlv_lsp++; } break; case ISIS_TLV_CHECKSUM: if (tmp < ISIS_TLV_CHECKSUM_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN); ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr))); /* do not attempt to verify the checksum if it is zero * most likely a HMAC-MD5 TLV is also present and * to avoid conflicts the checksum TLV is zeroed. * see rfc3358 for details */ osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr, length); break; case ISIS_TLV_POI: if (tlv_len >= SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s", isis_print_id(tptr + 1, SYSTEM_ID_LEN))); } if (tlv_len == 2 * SYSTEM_ID_LEN + 1) { ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1); ND_PRINT((ndo, "\n\t Received from System-ID: %s", isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN))); } break; case ISIS_TLV_MT_SUPPORTED: if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN) break; while (tmp>1) { /* length can only be a multiple of 2, otherwise there is something broken -> so decode down until length is 1 */ if (tmp!=1) { mt_len = isis_print_mtid(ndo, tptr, "\n\t "); if (mt_len == 0) /* did something go wrong ? */ goto trunctlv; tptr+=mt_len; tmp-=mt_len; } else { ND_PRINT((ndo, "\n\t invalid MT-ID")); break; } } break; case ISIS_TLV_RESTART_SIGNALING: /* first attempt to decode the flags */ if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN); ND_PRINT((ndo, "\n\t Flags [%s]", bittok2str(isis_restart_flag_values, "none", *tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; /* is there anything other than the flags field? */ if (tmp == 0) break; if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN) break; ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN); ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr))); tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; /* is there an additional sysid field present ?*/ if (tmp == SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN))); } break; case ISIS_TLV_IDRP_INFO: if (tmp < ISIS_TLV_IDRP_INFO_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN); ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s", tok2str(isis_subtlv_idrp_values, "Unknown (0x%02x)", *tptr))); switch (*tptr++) { case ISIS_SUBTLV_IDRP_ASN: ND_TCHECK2(*tptr, 2); /* fetch AS number */ ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr))); break; case ISIS_SUBTLV_IDRP_LOCAL: case ISIS_SUBTLV_IDRP_RES: default: if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1)) return(0); break; } break; case ISIS_TLV_LSP_BUFFERSIZE: if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN); ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr))); break; case ISIS_TLV_PART_DIS: while (tmp >= SYSTEM_ID_LEN) { ND_TCHECK2(*tptr, SYSTEM_ID_LEN); ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN))); tptr+=SYSTEM_ID_LEN; tmp-=SYSTEM_ID_LEN; } break; case ISIS_TLV_PREFIX_NEIGH: if (tmp < sizeof(struct isis_metric_block)) break; ND_TCHECK2(*tptr, sizeof(struct isis_metric_block)); ND_PRINT((ndo, "\n\t Metric Block")); isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr); tptr+=sizeof(struct isis_metric_block); tmp-=sizeof(struct isis_metric_block); while(tmp>0) { ND_TCHECK2(*tptr, 1); prefix_len=*tptr++; /* read out prefix length in semioctets*/ if (prefix_len < 2) { ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len)); break; } tmp--; if (tmp < prefix_len/2) break; ND_TCHECK2(*tptr, prefix_len / 2); ND_PRINT((ndo, "\n\t\tAddress: %s/%u", isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4)); tptr+=prefix_len/2; tmp-=prefix_len/2; } break; case ISIS_TLV_IIH_SEQNR: if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */ ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr))); break; case ISIS_TLV_VENDOR_PRIVATE: if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN) break; ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */ vendor_id = EXTRACT_24BITS(tptr); ND_PRINT((ndo, "\n\t Vendor: %s (%u)", tok2str(oui_values, "Unknown", vendor_id), vendor_id)); tptr+=3; tmp-=3; if (tmp > 0) /* hexdump the rest */ if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp)) return(0); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case ISIS_TLV_DECNET_PHASE4: case ISIS_TLV_LUCENT_PRIVATE: case ISIS_TLV_IPAUTH: case ISIS_TLV_NORTEL_PRIVATE1: case ISIS_TLV_NORTEL_PRIVATE2: default: if (ndo->ndo_vflag <= 1) { if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len)) return(0); } break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) { if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len)) return(0); } pptr += tlv_len; packet_len -= tlv_len; } if (packet_len != 0) { ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len)); } return (1); trunc: ND_PRINT((ndo, "%s", tstr)); return (1); trunctlv: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } static void osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr, uint16_t checksum, int checksum_offset, u_int length) { uint16_t calculated_checksum; /* do not attempt to verify the checksum if it is zero, * if the offset is nonsense, * or the base pointer is not sane */ if (!checksum || checksum_offset < 0 || !ND_TTEST2(*(pptr + checksum_offset), 2) || (u_int)checksum_offset > length || !ND_TTEST2(*pptr, length)) { ND_PRINT((ndo, " (unverified)")); } else { #if 0 printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length); #endif calculated_checksum = create_osi_cksum(pptr, checksum_offset, length); if (checksum == calculated_checksum) { ND_PRINT((ndo, " (correct)")); } else { ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum)); } } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2731_0
crossvul-cpp_data_bad_3870_0
/* * The Python Imaging Library. * $Id$ * * decoder for PCX image data. * * history: * 95-09-14 fl Created * * Copyright (c) Fredrik Lundh 1995. * Copyright (c) Secret Labs AB 1997. * * See the README file for information on usage and redistribution. */ #include "Imaging.h" int ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if (strcmp(im->mode, "1") == 0 && state->xsize > state->bytes * 8) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } else if (strcmp(im->mode, "P") == 0 && state->xsize > state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3870_0
crossvul-cpp_data_good_2710_0
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Andy Heffernan (ahh@juniper.net) */ /* \summary: Pragmatic General Multicast (PGM) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "addrtostr.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" #include "af.h" /* * PGM header (RFC 3208) */ struct pgm_header { uint16_t pgm_sport; uint16_t pgm_dport; uint8_t pgm_type; uint8_t pgm_options; uint16_t pgm_sum; uint8_t pgm_gsid[6]; uint16_t pgm_length; }; struct pgm_spm { uint32_t pgms_seq; uint32_t pgms_trailseq; uint32_t pgms_leadseq; uint16_t pgms_nla_afi; uint16_t pgms_reserved; /* ... uint8_t pgms_nla[0]; */ /* ... options */ }; struct pgm_nak { uint32_t pgmn_seq; uint16_t pgmn_source_afi; uint16_t pgmn_reserved; /* ... uint8_t pgmn_source[0]; */ /* ... uint16_t pgmn_group_afi */ /* ... uint16_t pgmn_reserved2; */ /* ... uint8_t pgmn_group[0]; */ /* ... options */ }; struct pgm_ack { uint32_t pgma_rx_max_seq; uint32_t pgma_bitmap; /* ... options */ }; struct pgm_poll { uint32_t pgmp_seq; uint16_t pgmp_round; uint16_t pgmp_reserved; /* ... options */ }; struct pgm_polr { uint32_t pgmp_seq; uint16_t pgmp_round; uint16_t pgmp_subtype; uint16_t pgmp_nla_afi; uint16_t pgmp_reserved; /* ... uint8_t pgmp_nla[0]; */ /* ... options */ }; struct pgm_data { uint32_t pgmd_seq; uint32_t pgmd_trailseq; /* ... options */ }; typedef enum _pgm_type { PGM_SPM = 0, /* source path message */ PGM_POLL = 1, /* POLL Request */ PGM_POLR = 2, /* POLL Response */ PGM_ODATA = 4, /* original data */ PGM_RDATA = 5, /* repair data */ PGM_NAK = 8, /* NAK */ PGM_NULLNAK = 9, /* Null NAK */ PGM_NCF = 10, /* NAK Confirmation */ PGM_ACK = 11, /* ACK for congestion control */ PGM_SPMR = 12, /* SPM request */ PGM_MAX = 255 } pgm_type; #define PGM_OPT_BIT_PRESENT 0x01 #define PGM_OPT_BIT_NETWORK 0x02 #define PGM_OPT_BIT_VAR_PKTLEN 0x40 #define PGM_OPT_BIT_PARITY 0x80 #define PGM_OPT_LENGTH 0x00 #define PGM_OPT_FRAGMENT 0x01 #define PGM_OPT_NAK_LIST 0x02 #define PGM_OPT_JOIN 0x03 #define PGM_OPT_NAK_BO_IVL 0x04 #define PGM_OPT_NAK_BO_RNG 0x05 #define PGM_OPT_REDIRECT 0x07 #define PGM_OPT_PARITY_PRM 0x08 #define PGM_OPT_PARITY_GRP 0x09 #define PGM_OPT_CURR_TGSIZE 0x0A #define PGM_OPT_NBR_UNREACH 0x0B #define PGM_OPT_PATH_NLA 0x0C #define PGM_OPT_SYN 0x0D #define PGM_OPT_FIN 0x0E #define PGM_OPT_RST 0x0F #define PGM_OPT_CR 0x10 #define PGM_OPT_CRQST 0x11 #define PGM_OPT_PGMCC_DATA 0x12 #define PGM_OPT_PGMCC_FEEDBACK 0x13 #define PGM_OPT_MASK 0x7f #define PGM_OPT_END 0x80 /* end of options marker */ #define PGM_MIN_OPT_LEN 4 void pgm_print(netdissect_options *ndo, register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct pgm_header *pgm; register const struct ip *ip; register char ch; uint16_t sport, dport; u_int nla_afnum; char nla_buf[INET6_ADDRSTRLEN]; register const struct ip6_hdr *ip6; uint8_t opt_type, opt_len; uint32_t seq, opts_len, len, offset; pgm = (const struct pgm_header *)bp; ip = (const struct ip *)bp2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)bp2; else ip6 = NULL; ch = '\0'; if (!ND_TTEST(pgm->pgm_dport)) { if (ip6) { ND_PRINT((ndo, "%s > %s: [|pgm]", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); } else { ND_PRINT((ndo, "%s > %s: [|pgm]", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); } return; } sport = EXTRACT_16BITS(&pgm->pgm_sport); dport = EXTRACT_16BITS(&pgm->pgm_dport); if (ip6) { if (ip6->ip6_nxt == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ip6addr_string(ndo, &ip6->ip6_src), tcpport_string(ndo, sport), ip6addr_string(ndo, &ip6->ip6_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } else { if (ip->ip_p == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ipaddr_string(ndo, &ip->ip_src), tcpport_string(ndo, sport), ipaddr_string(ndo, &ip->ip_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } ND_TCHECK(*pgm); ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length))); if (!ndo->ndo_vflag) return; ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ", pgm->pgm_gsid[0], pgm->pgm_gsid[1], pgm->pgm_gsid[2], pgm->pgm_gsid[3], pgm->pgm_gsid[4], pgm->pgm_gsid[5])); switch (pgm->pgm_type) { case PGM_SPM: { const struct pgm_spm *spm; spm = (const struct pgm_spm *)(pgm + 1); ND_TCHECK(*spm); bp = (const u_char *) (spm + 1); switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s", EXTRACT_32BITS(&spm->pgms_seq), EXTRACT_32BITS(&spm->pgms_trailseq), EXTRACT_32BITS(&spm->pgms_leadseq), nla_buf)); break; } case PGM_POLL: { const struct pgm_poll *poll_msg; poll_msg = (const struct pgm_poll *)(pgm + 1); ND_TCHECK(*poll_msg); ND_PRINT((ndo, "POLL seq %u round %u", EXTRACT_32BITS(&poll_msg->pgmp_seq), EXTRACT_16BITS(&poll_msg->pgmp_round))); bp = (const u_char *) (poll_msg + 1); break; } case PGM_POLR: { const struct pgm_polr *polr; uint32_t ivl, rnd, mask; polr = (const struct pgm_polr *)(pgm + 1); ND_TCHECK(*polr); bp = (const u_char *) (polr + 1); switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_TCHECK2(*bp, sizeof(uint32_t)); ivl = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); rnd = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); mask = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x " "mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq), EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask)); break; } case PGM_ODATA: { const struct pgm_data *odata; odata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*odata); ND_PRINT((ndo, "ODATA trail %u seq %u", EXTRACT_32BITS(&odata->pgmd_trailseq), EXTRACT_32BITS(&odata->pgmd_seq))); bp = (const u_char *) (odata + 1); break; } case PGM_RDATA: { const struct pgm_data *rdata; rdata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*rdata); ND_PRINT((ndo, "RDATA trail %u seq %u", EXTRACT_32BITS(&rdata->pgmd_trailseq), EXTRACT_32BITS(&rdata->pgmd_seq))); bp = (const u_char *) (rdata + 1); break; } case PGM_NAK: case PGM_NULLNAK: case PGM_NCF: { const struct pgm_nak *nak; char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN]; nak = (const struct pgm_nak *)(pgm + 1); ND_TCHECK(*nak); bp = (const u_char *) (nak + 1); /* * Skip past the source, saving info along the way * and stopping if we don't have enough. */ switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Skip past the group, saving info along the way * and stopping if we don't have enough. */ bp += (2 * sizeof(uint16_t)); ND_TCHECK_16BITS(bp); switch (EXTRACT_16BITS(bp)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Options decoding can go here. */ switch (pgm->pgm_type) { case PGM_NAK: ND_PRINT((ndo, "NAK ")); break; case PGM_NULLNAK: ND_PRINT((ndo, "NNAK ")); break; case PGM_NCF: ND_PRINT((ndo, "NCF ")); break; default: break; } ND_PRINT((ndo, "(%s -> %s), seq %u", source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq))); break; } case PGM_ACK: { const struct pgm_ack *ack; ack = (const struct pgm_ack *)(pgm + 1); ND_TCHECK(*ack); ND_PRINT((ndo, "ACK seq %u", EXTRACT_32BITS(&ack->pgma_rx_max_seq))); bp = (const u_char *) (ack + 1); break; } case PGM_SPMR: ND_PRINT((ndo, "SPMR")); break; default: ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type)); break; } if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) { /* * make sure there's enough for the first option header */ if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) { ND_PRINT((ndo, "[|OPT]")); return; } /* * That option header MUST be an OPT_LENGTH option * (see the first paragraph of section 9.1 in RFC 3208). */ opt_type = *bp++; if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) { ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK)); return; } opt_len = *bp++; if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } opts_len = EXTRACT_16BITS(bp); if (opts_len < 4) { ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len)); return; } bp += sizeof(uint16_t); ND_PRINT((ndo, " OPTS LEN %d", opts_len)); opts_len -= 4; while (opts_len) { if (opts_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, 2)) { ND_PRINT((ndo, " [|OPT]")); return; } opt_type = *bp++; opt_len = *bp++; if (opt_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len, PGM_MIN_OPT_LEN)); break; } if (opts_len < opt_len) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, opt_len - 2)) { ND_PRINT((ndo, " [|OPT]")); return; } switch (opt_type & PGM_OPT_MASK) { case PGM_OPT_LENGTH: #define PGM_OPT_LENGTH_LEN (2+2) if (opt_len != PGM_OPT_LENGTH_LEN) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != %u]", opt_len, PGM_OPT_LENGTH_LEN)); return; } ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp))); bp += 2; opts_len -= PGM_OPT_LENGTH_LEN; break; case PGM_OPT_FRAGMENT: #define PGM_OPT_FRAGMENT_LEN (2+2+4+4+4) if (opt_len != PGM_OPT_FRAGMENT_LEN) { ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != %u]", opt_len, PGM_OPT_FRAGMENT_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; offset = EXTRACT_32BITS(bp); bp += 4; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len)); opts_len -= PGM_OPT_FRAGMENT_LEN; break; case PGM_OPT_NAK_LIST: bp += 2; opt_len -= 4; /* option header */ ND_PRINT((ndo, " NAK LIST")); while (opt_len) { if (opt_len < 4) { ND_PRINT((ndo, "[Option length not a multiple of 4]")); return; } ND_TCHECK2(*bp, 4); ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp))); bp += 4; opt_len -= 4; opts_len -= 4; } break; case PGM_OPT_JOIN: #define PGM_OPT_JOIN_LEN (2+2+4) if (opt_len != PGM_OPT_JOIN_LEN) { ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != %u]", opt_len, PGM_OPT_JOIN_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " JOIN %u", seq)); opts_len -= PGM_OPT_JOIN_LEN; break; case PGM_OPT_NAK_BO_IVL: #define PGM_OPT_NAK_BO_IVL_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_IVL_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_IVL_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_IVL_LEN; break; case PGM_OPT_NAK_BO_RNG: #define PGM_OPT_NAK_BO_RNG_LEN (2+2+4+4) if (opt_len != PGM_OPT_NAK_BO_RNG_LEN) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != %u]", opt_len, PGM_OPT_NAK_BO_RNG_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq)); opts_len -= PGM_OPT_NAK_BO_RNG_LEN; break; case PGM_OPT_REDIRECT: #define PGM_OPT_REDIRECT_FIXED_LEN (2+2+2+2) if (opt_len < PGM_OPT_REDIRECT_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u < %u]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } bp += 2; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", opt_len, PGM_OPT_REDIRECT_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]", PGM_OPT_REDIRECT_FIXED_LEN, opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " REDIRECT %s", nla_buf)); break; case PGM_OPT_PARITY_PRM: #define PGM_OPT_PARITY_PRM_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_PRM_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != %u]", opt_len, PGM_OPT_PARITY_PRM_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY MAXTGS %u", len)); opts_len -= PGM_OPT_PARITY_PRM_LEN; break; case PGM_OPT_PARITY_GRP: #define PGM_OPT_PARITY_GRP_LEN (2+2+4) if (opt_len != PGM_OPT_PARITY_GRP_LEN) { ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != %u]", opt_len, PGM_OPT_PARITY_GRP_LEN)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY GROUP %u", seq)); opts_len -= PGM_OPT_PARITY_GRP_LEN; break; case PGM_OPT_CURR_TGSIZE: #define PGM_OPT_CURR_TGSIZE_LEN (2+2+4) if (opt_len != PGM_OPT_CURR_TGSIZE_LEN) { ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != %u]", opt_len, PGM_OPT_CURR_TGSIZE_LEN)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += 4; ND_PRINT((ndo, " PARITY ATGS %u", len)); opts_len -= PGM_OPT_CURR_TGSIZE_LEN; break; case PGM_OPT_NBR_UNREACH: #define PGM_OPT_NBR_UNREACH_LEN (2+2) if (opt_len != PGM_OPT_NBR_UNREACH_LEN) { ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != %u]", opt_len, PGM_OPT_NBR_UNREACH_LEN)); return; } bp += 2; ND_PRINT((ndo, " NBR_UNREACH")); opts_len -= PGM_OPT_NBR_UNREACH_LEN; break; case PGM_OPT_PATH_NLA: ND_PRINT((ndo, " PATH_NLA [%d]", opt_len)); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_SYN: #define PGM_OPT_SYN_LEN (2+2) if (opt_len != PGM_OPT_SYN_LEN) { ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != %u]", opt_len, PGM_OPT_SYN_LEN)); return; } bp += 2; ND_PRINT((ndo, " SYN")); opts_len -= PGM_OPT_SYN_LEN; break; case PGM_OPT_FIN: #define PGM_OPT_FIN_LEN (2+2) if (opt_len != PGM_OPT_FIN_LEN) { ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != %u]", opt_len, PGM_OPT_FIN_LEN)); return; } bp += 2; ND_PRINT((ndo, " FIN")); opts_len -= PGM_OPT_FIN_LEN; break; case PGM_OPT_RST: #define PGM_OPT_RST_LEN (2+2) if (opt_len != PGM_OPT_RST_LEN) { ND_PRINT((ndo, "[Bad OPT_RST option, length %u != %u]", opt_len, PGM_OPT_RST_LEN)); return; } bp += 2; ND_PRINT((ndo, " RST")); opts_len -= PGM_OPT_RST_LEN; break; case PGM_OPT_CR: ND_PRINT((ndo, " CR")); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_CRQST: #define PGM_OPT_CRQST_LEN (2+2) if (opt_len != PGM_OPT_CRQST_LEN) { ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != %u]", opt_len, PGM_OPT_CRQST_LEN)); return; } bp += 2; ND_PRINT((ndo, " CRQST")); opts_len -= PGM_OPT_CRQST_LEN; break; case PGM_OPT_PGMCC_DATA: #define PGM_OPT_PGMCC_DATA_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_DATA_FIXED_LEN) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u < %u]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf)); break; case PGM_OPT_PGMCC_FEEDBACK: #define PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN (2+2+4+2+2) if (opt_len < PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN) { ND_PRINT((ndo, "[Bad PGM_OPT_PGMCC_FEEDBACK option, length %u < %u]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += 4; nla_afnum = EXTRACT_16BITS(bp); bp += 2+2; switch (nla_afnum) { case AFNUM_INET: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]", opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf)); break; default: ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len)); bp += opt_len; opts_len -= opt_len; break; } if (opt_type & PGM_OPT_END) break; } } ND_PRINT((ndo, " [%u]", length)); if (ndo->ndo_packettype == PT_PGM_ZMTP1 && (pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA)) zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length)); return; trunc: ND_PRINT((ndo, "[|pgm]")); if (ch != '\0') ND_PRINT((ndo, ">")); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2710_0
crossvul-cpp_data_good_4215_0
/* * ndpiReader.c * * Copyright (C) 2011-19 - ntop.org * * nDPI 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 3 of the License, or * (at your option) any later version. * * nDPI 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 nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_config.h" #ifdef linux #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <sched.h> #endif #include <stdio.h> #include <stdlib.h> #include <getopt.h> #ifdef WIN32 #include <winsock2.h> /* winsock.h is included automatically */ #include <process.h> #include <io.h> #define getopt getopt____ #else #include <unistd.h> #include <netinet/in.h> #endif #include <string.h> #include <stdarg.h> #include <search.h> #include <pcap.h> #include <signal.h> #include <pthread.h> #include <sys/socket.h> #include <assert.h> #include <math.h> #include "ndpi_api.h" #include "uthash.h" #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <libgen.h> #include "reader_util.h" #include "intrusion_detection.h" /** Client parameters **/ static char *_pcap_file[MAX_NUM_READER_THREADS]; /**< Ingress pcap file/interfaces */ static FILE *playlist_fp[MAX_NUM_READER_THREADS] = { NULL }; /**< Ingress playlist */ static FILE *results_file = NULL; static char *results_path = NULL; static char * bpfFilter = NULL; /**< bpf filter */ static char *_protoFilePath = NULL; /**< Protocol file path */ static char *_customCategoryFilePath= NULL; /**< Custom categories file path */ static FILE *csv_fp = NULL; /**< for CSV export */ static u_int8_t live_capture = 0; static u_int8_t undetected_flows_deleted = 0; /** User preferences **/ u_int8_t enable_protocol_guess = 1, enable_payload_analyzer = 0; u_int8_t verbose = 0, enable_joy_stats = 0; int nDPI_LogLevel = 0; char *_debug_protocols = NULL; u_int8_t human_readeable_string_len = 5; u_int8_t max_num_udp_dissected_pkts = 16 /* 8 is enough for most protocols, Signal requires more */, max_num_tcp_dissected_pkts = 80 /* due to telnet */; static u_int32_t pcap_analysis_duration = (u_int32_t)-1; static u_int16_t decode_tunnels = 0; static u_int16_t num_loops = 1; static u_int8_t shutdown_app = 0, quiet_mode = 0; static u_int8_t num_threads = 1; static struct timeval startup_time, begin, end; #ifdef linux static int core_affinity[MAX_NUM_READER_THREADS]; #endif static struct timeval pcap_start = { 0, 0}, pcap_end = { 0, 0 }; /** Detection parameters **/ static time_t capture_for = 0; static time_t capture_until = 0; static u_int32_t num_flows; static struct ndpi_detection_module_struct *ndpi_info_mod = NULL; extern u_int32_t max_num_packets_per_flow, max_packet_payload_dissection, max_num_reported_top_payloads; extern u_int16_t min_pattern_len, max_pattern_len; extern void ndpi_self_check_host_match(); /* Self check function */ struct flow_info { struct ndpi_flow_info *flow; u_int16_t thread_id; }; static struct flow_info *all_flows; struct info_pair { u_int32_t addr; u_int8_t version; /* IP version */ char proto[16]; /*app level protocol*/ int count; }; typedef struct node_a{ u_int32_t addr; u_int8_t version; /* IP version */ char proto[16]; /*app level protocol*/ int count; struct node_a *left, *right; }addr_node; struct port_stats { u_int32_t port; /* we'll use this field as the key */ u_int32_t num_pkts, num_bytes; u_int32_t num_flows; u_int32_t num_addr; /*number of distinct IP addresses */ u_int32_t cumulative_addr; /*cumulative some of IP addresses */ addr_node *addr_tree; /* tree of distinct IP addresses */ struct info_pair top_ip_addrs[MAX_NUM_IP_ADDRESS]; u_int8_t hasTopHost; /* as boolean flag */ u_int32_t top_host; /* host that is contributed to > 95% of traffic */ u_int8_t version; /* top host's ip version */ char proto[16]; /* application level protocol of top host */ UT_hash_handle hh; /* makes this structure hashable */ }; struct port_stats *srcStats = NULL, *dstStats = NULL; // struct to hold count of flows received by destination ports struct port_flow_info { u_int32_t port; /* key */ u_int32_t num_flows; UT_hash_handle hh; }; // struct to hold single packet tcp flows sent by source ip address struct single_flow_info { u_int32_t saddr; /* key */ u_int8_t version; /* IP version */ struct port_flow_info *ports; u_int32_t tot_flows; UT_hash_handle hh; }; struct single_flow_info *scannerHosts = NULL; // struct to hold top receiver hosts struct receiver { u_int32_t addr; /* key */ u_int8_t version; /* IP version */ u_int32_t num_pkts; UT_hash_handle hh; }; struct receiver *receivers = NULL, *topReceivers = NULL; struct ndpi_packet_trailer { u_int32_t magic; /* 0x19682017 */ u_int16_t master_protocol /* e.g. HTTP */, app_protocol /* e.g. FaceBook */; char name[16]; }; static pcap_dumper_t *extcap_dumper = NULL; static char extcap_buf[16384]; static char *extcap_capture_fifo = NULL; static u_int16_t extcap_packet_filter = (u_int16_t)-1; // struct associated to a workflow for a thread struct reader_thread { struct ndpi_workflow *workflow; pthread_t pthread; u_int64_t last_idle_scan_time; u_int32_t idle_scan_idx; u_int32_t num_idle_flows; struct ndpi_flow_info *idle_flows[IDLE_SCAN_BUDGET]; }; // array for every thread created for a flow static struct reader_thread ndpi_thread_info[MAX_NUM_READER_THREADS]; // ID tracking typedef struct ndpi_id { u_int8_t ip[4]; // Ip address struct ndpi_id_struct *ndpi_id; // nDpi worker structure } ndpi_id_t; // used memory counters u_int32_t current_ndpi_memory = 0, max_ndpi_memory = 0; #ifdef USE_DPDK static int dpdk_port_id = 0, dpdk_run_capture = 1; #endif void test_lib(); /* Forward */ extern void ndpi_report_payload_stats(); /* ********************************** */ #ifdef DEBUG_TRACE FILE *trace = NULL; #endif /********************** FUNCTIONS ********************* */ /** * @brief Set main components necessary to the detection */ static void setupDetection(u_int16_t thread_id, pcap_t * pcap_handle); #if 0 static void reduceBDbits(uint32_t *bd, unsigned int len) { int mask = 0; int shift = 0; unsigned int i = 0; for(i = 0; i < len; i++) mask = mask | bd[i]; mask = mask >> 8; for(i = 0; i < 24 && mask; i++) { mask = mask >> 1; if (mask == 0) { shift = i+1; break; } } for(i = 0; i < len; i++) bd[i] = bd[i] >> shift; } #endif /** * @brief Get flow byte distribution mean and variance */ static void flowGetBDMeanandVariance(struct ndpi_flow_info* flow) { FILE *out = results_file ? results_file : stdout; const uint32_t *array = NULL; uint32_t tmp[256], i; unsigned int num_bytes; double mean = 0.0, variance = 0.0; struct ndpi_entropy last_entropy = flow->last_entropy; fflush(out); /* * Sum up the byte_count array for outbound and inbound flows, * if this flow is bidirectional */ if (!flow->bidirectional) { array = last_entropy.src2dst_byte_count; num_bytes = last_entropy.src2dst_l4_bytes; for (i=0; i<256; i++) { tmp[i] = last_entropy.src2dst_byte_count[i]; } if (last_entropy.src2dst_num_bytes != 0) { mean = last_entropy.src2dst_bd_mean; variance = last_entropy.src2dst_bd_variance/(last_entropy.src2dst_num_bytes - 1); variance = sqrt(variance); if (last_entropy.src2dst_num_bytes == 1) { variance = 0.0; } } } else { for (i=0; i<256; i++) { tmp[i] = last_entropy.src2dst_byte_count[i] + last_entropy.dst2src_byte_count[i]; } array = tmp; num_bytes = last_entropy.src2dst_l4_bytes + last_entropy.dst2src_l4_bytes; if (last_entropy.src2dst_num_bytes + last_entropy.dst2src_num_bytes != 0) { mean = ((double)last_entropy.src2dst_num_bytes)/((double)(last_entropy.src2dst_num_bytes+last_entropy.dst2src_num_bytes))*last_entropy.src2dst_bd_mean + ((double)last_entropy.dst2src_num_bytes)/((double)(last_entropy.dst2src_num_bytes+last_entropy.src2dst_num_bytes))*last_entropy.dst2src_bd_mean; variance = ((double)last_entropy.src2dst_num_bytes)/((double)(last_entropy.src2dst_num_bytes+last_entropy.dst2src_num_bytes))*last_entropy.src2dst_bd_variance + ((double)last_entropy.dst2src_num_bytes)/((double)(last_entropy.dst2src_num_bytes+last_entropy.src2dst_num_bytes))*last_entropy.dst2src_bd_variance; variance = variance/((double)(last_entropy.src2dst_num_bytes + last_entropy.dst2src_num_bytes - 1)); variance = sqrt(variance); if (last_entropy.src2dst_num_bytes + last_entropy.dst2src_num_bytes == 1) { variance = 0.0; } } } if(enable_joy_stats) { #if 0 if(verbose > 1) { reduceBDbits(tmp, 256); array = tmp; fprintf(out, " [byte_dist: "); for(i = 0; i < 255; i++) fprintf(out, "%u,", (unsigned char)array[i]); fprintf(out, "%u]", (unsigned char)array[i]); } #endif /* Output the mean */ if(num_bytes != 0) { double entropy = ndpi_flow_get_byte_count_entropy(array, num_bytes); if(csv_fp) { fprintf(csv_fp, ",%.3f,%.3f,%.3f,%.3f", mean, variance, entropy, entropy * num_bytes); } else { fprintf(out, "[byte_dist_mean: %f", mean); fprintf(out, "][byte_dist_std: %f]", variance); fprintf(out, "[entropy: %f]", entropy); fprintf(out, "[total_entropy: %f]", entropy * num_bytes); } } else { if(csv_fp) fprintf(csv_fp, ",%.3f,%.3f,%.3f,%.3f", 0.0, 0.0, 0.0, 0.0); } } } /** * @brief Print help instructions */ static void help(u_int long_help) { printf("Welcome to nDPI %s\n\n", ndpi_revision()); printf("ndpiReader " #ifndef USE_DPDK "-i <file|device> " #endif "[-f <filter>][-s <duration>][-m <duration>]\n" " [-p <protos>][-l <loops> [-q][-d][-J][-h][-e <len>][-t][-v <level>]\n" " [-n <threads>][-w <file>][-c <file>][-C <file>][-j <file>][-x <file>]\n" " [-T <num>][-U <num>]\n\n" "Usage:\n" " -i <file.pcap|device> | Specify a pcap file/playlist to read packets from or a\n" " | device for live capture (comma-separated list)\n" " -f <BPF filter> | Specify a BPF filter for filtering selected traffic\n" " -s <duration> | Maximum capture duration in seconds (live traffic capture only)\n" " -m <duration> | Split analysis duration in <duration> max seconds\n" " -p <file>.protos | Specify a protocol file (eg. protos.txt)\n" " -l <num loops> | Number of detection loops (test only)\n" " -n <num threads> | Number of threads. Default: number of interfaces in -i.\n" " | Ignored with pcap files.\n" #ifdef linux " -g <id:id...> | Thread affinity mask (one core id per thread)\n" #endif " -d | Disable protocol guess and use only DPI\n" " -e <len> | Min human readeable string match len. Default %u\n" " -q | Quiet mode\n" " -J | Display flow SPLT (sequence of packet length and time)\n" " | and BD (byte distribution). See https://github.com/cisco/joy\n" " -t | Dissect GTP/TZSP tunnels\n" " -P <a>:<b>:<c>:<d>:<e> | Enable payload analysis:\n" " | <a> = min pattern len to search\n" " | <b> = max pattern len to search\n" " | <c> = max num packets per flow\n" " | <d> = max packet payload dissection\n" " | <d> = max num reported payloads\n" " | Default: %u:%u:%u:%u:%u\n" " -r | Print nDPI version and git revision\n" " -c <path> | Load custom categories from the specified file\n" " -C <path> | Write output in CSV format on the specified file\n" " -w <path> | Write test output on the specified file. This is useful for\n" " | testing purposes in order to compare results across runs\n" " -h | This help\n" " -v <1|2|3> | Verbose 'unknown protocol' packet print.\n" " | 1 = verbose\n" " | 2 = very verbose\n" " | 3 = port stats\n" " -V <1-4> | nDPI logging level\n" " | 1 - trace, 2 - debug, 3 - full debug\n" " | >3 - full debug + dbg_proto = all\n" " -T <num> | Max number of TCP processed packets before giving up [default: %u]\n" " -U <num> | Max number of UDP processed packets before giving up [default: %u]\n" , human_readeable_string_len, min_pattern_len, max_pattern_len, max_num_packets_per_flow, max_packet_payload_dissection, max_num_reported_top_payloads, max_num_tcp_dissected_pkts, max_num_udp_dissected_pkts); #ifndef WIN32 printf("\nExcap (wireshark) options:\n" " --extcap-interfaces\n" " --extcap-version\n" " --extcap-dlts\n" " --extcap-interface <name>\n" " --extcap-config\n" " --capture\n" " --extcap-capture-filter\n" " --fifo <path to file or pipe>\n" " --debug\n" " --dbg-proto proto|num[,...]\n" ); #endif if(long_help) { NDPI_PROTOCOL_BITMASK all; printf("\n\nnDPI supported protocols:\n"); printf("%3s %-22s %-8s %-12s %s\n", "Id", "Protocol", "Layer_4", "Breed", "Category"); num_threads = 1; NDPI_BITMASK_SET_ALL(all); ndpi_set_protocol_detection_bitmask2(ndpi_info_mod, &all); ndpi_dump_protocols(ndpi_info_mod); } exit(!long_help); } static struct option longopts[] = { /* mandatory extcap options */ { "extcap-interfaces", no_argument, NULL, '0'}, { "extcap-version", optional_argument, NULL, '1'}, { "extcap-dlts", no_argument, NULL, '2'}, { "extcap-interface", required_argument, NULL, '3'}, { "extcap-config", no_argument, NULL, '4'}, { "capture", no_argument, NULL, '5'}, { "extcap-capture-filter", required_argument, NULL, '6'}, { "fifo", required_argument, NULL, '7'}, { "debug", no_argument, NULL, '8'}, { "dbg-proto", required_argument, NULL, 257}, { "ndpi-proto-filter", required_argument, NULL, '9'}, /* ndpiReader options */ { "enable-protocol-guess", no_argument, NULL, 'd'}, { "categories", required_argument, NULL, 'c'}, { "csv-dump", required_argument, NULL, 'C'}, { "interface", required_argument, NULL, 'i'}, { "filter", required_argument, NULL, 'f'}, { "cpu-bind", required_argument, NULL, 'g'}, { "loops", required_argument, NULL, 'l'}, { "num-threads", required_argument, NULL, 'n'}, { "protos", required_argument, NULL, 'p'}, { "capture-duration", required_argument, NULL, 's'}, { "decode-tunnels", no_argument, NULL, 't'}, { "revision", no_argument, NULL, 'r'}, { "verbose", no_argument, NULL, 'v'}, { "version", no_argument, NULL, 'V'}, { "help", no_argument, NULL, 'h'}, { "joy", required_argument, NULL, 'J'}, { "payload-analysis", required_argument, NULL, 'P'}, { "result-path", required_argument, NULL, 'w'}, { "quiet", no_argument, NULL, 'q'}, {0, 0, 0, 0} }; /* ********************************** */ void extcap_interfaces() { printf("extcap {version=%s}\n", ndpi_revision()); printf("interface {value=ndpi}{display=nDPI interface}\n"); exit(0); } /* ********************************** */ void extcap_dlts() { u_int dlts_number = DLT_EN10MB; printf("dlt {number=%u}{name=%s}{display=%s}\n", dlts_number, "ndpi", "nDPI Interface"); exit(0); } /* ********************************** */ struct ndpi_proto_sorter { int id; char name[16]; }; /* ********************************** */ int cmpProto(const void *_a, const void *_b) { struct ndpi_proto_sorter *a = (struct ndpi_proto_sorter*)_a; struct ndpi_proto_sorter *b = (struct ndpi_proto_sorter*)_b; return(strcmp(a->name, b->name)); } /* ********************************** */ int cmpFlows(const void *_a, const void *_b) { struct ndpi_flow_info *fa = ((struct flow_info*)_a)->flow; struct ndpi_flow_info *fb = ((struct flow_info*)_b)->flow; uint64_t a_size = fa->src2dst_bytes + fa->dst2src_bytes; uint64_t b_size = fb->src2dst_bytes + fb->dst2src_bytes; if(a_size != b_size) return a_size < b_size ? 1 : -1; // copy from ndpi_workflow_node_cmp(); if(fa->ip_version < fb->ip_version ) return(-1); else { if(fa->ip_version > fb->ip_version ) return(1); } if(fa->protocol < fb->protocol ) return(-1); else { if(fa->protocol > fb->protocol ) return(1); } if(htonl(fa->src_ip) < htonl(fb->src_ip) ) return(-1); else { if(htonl(fa->src_ip) > htonl(fb->src_ip) ) return(1); } if(htons(fa->src_port) < htons(fb->src_port)) return(-1); else { if(htons(fa->src_port) > htons(fb->src_port)) return(1); } if(htonl(fa->dst_ip) < htonl(fb->dst_ip) ) return(-1); else { if(htonl(fa->dst_ip) > htonl(fb->dst_ip) ) return(1); } if(htons(fa->dst_port) < htons(fb->dst_port)) return(-1); else { if(htons(fa->dst_port) > htons(fb->dst_port)) return(1); } return(0); } /* ********************************** */ void extcap_config() { int i, argidx = 0; struct ndpi_proto_sorter *protos; u_int ndpi_num_supported_protocols = ndpi_get_ndpi_num_supported_protocols(ndpi_info_mod); ndpi_proto_defaults_t *proto_defaults = ndpi_get_proto_defaults(ndpi_info_mod); /* -i <interface> */ printf("arg {number=%d}{call=-i}{display=Capture Interface}{type=string}" "{tooltip=The interface name}\n", argidx++); printf("arg {number=%d}{call=-i}{display=Pcap File to Analyze}{type=fileselect}" "{tooltip=The pcap file to analyze (if the interface is unspecified)}\n", argidx++); protos = (struct ndpi_proto_sorter*)malloc(sizeof(struct ndpi_proto_sorter) * ndpi_num_supported_protocols); if(!protos) exit(0); for(i=0; i<(int) ndpi_num_supported_protocols; i++) { protos[i].id = i; snprintf(protos[i].name, sizeof(protos[i].name), "%s", proto_defaults[i].protoName); } qsort(protos, ndpi_num_supported_protocols, sizeof(struct ndpi_proto_sorter), cmpProto); printf("arg {number=%d}{call=-9}{display=nDPI Protocol Filter}{type=selector}" "{tooltip=nDPI Protocol to be filtered}\n", argidx); printf("value {arg=%d}{value=%d}{display=%s}\n", argidx, -1, "All Protocols (no nDPI filtering)"); for(i=0; i<(int)ndpi_num_supported_protocols; i++) printf("value {arg=%d}{value=%d}{display=%s (%d)}\n", argidx, protos[i].id, protos[i].name, protos[i].id); free(protos); exit(0); } /* ********************************** */ void extcap_capture() { #ifdef DEBUG_TRACE if(trace) fprintf(trace, " #### %s #### \n", __FUNCTION__); #endif if((extcap_dumper = pcap_dump_open(pcap_open_dead(DLT_EN10MB, 16384 /* MTU */), extcap_capture_fifo)) == NULL) { fprintf(stderr, "Unable to open the pcap dumper on %s", extcap_capture_fifo); #ifdef DEBUG_TRACE if(trace) fprintf(trace, "Unable to open the pcap dumper on %s\n", extcap_capture_fifo); #endif return; } #ifdef DEBUG_TRACE if(trace) fprintf(trace, "Starting packet capture [%p]\n", extcap_dumper); #endif } /* ********************************** */ void printCSVHeader() { if(!csv_fp) return; fprintf(csv_fp, "#flow_id,protocol,first_seen,last_seen,duration,src_ip,src_port,dst_ip,dst_port,ndpi_proto_num,ndpi_proto,server_name,"); fprintf(csv_fp, "benign_score,dos_slow_score,dos_goldeneye_score,dos_hulk_score,ddos_score,hearthbleed_score,ftp_patator_score,ssh_patator_score,infiltration_score,"); fprintf(csv_fp, "c_to_s_pkts,c_to_s_bytes,c_to_s_goodput_bytes,s_to_c_pkts,s_to_c_bytes,s_to_c_goodput_bytes,"); fprintf(csv_fp, "data_ratio,str_data_ratio,c_to_s_goodput_ratio,s_to_c_goodput_ratio,"); /* IAT (Inter Arrival Time) */ fprintf(csv_fp, "iat_flow_min,iat_flow_avg,iat_flow_max,iat_flow_stddev,"); fprintf(csv_fp, "iat_c_to_s_min,iat_c_to_s_avg,iat_c_to_s_max,iat_c_to_s_stddev,"); fprintf(csv_fp, "iat_s_to_c_min,iat_s_to_c_avg,iat_s_to_c_max,iat_s_to_c_stddev,"); /* Packet Length */ fprintf(csv_fp, "pktlen_c_to_s_min,pktlen_c_to_s_avg,pktlen_c_to_s_max,pktlen_c_to_s_stddev,"); fprintf(csv_fp, "pktlen_s_to_c_min,pktlen_s_to_c_avg,pktlen_s_to_c_max,pktlen_s_to_c_stddev,"); /* TCP flags */ fprintf(csv_fp, "cwr,ece,urg,ack,psh,rst,syn,fin,"); fprintf(csv_fp, "c_to_s_cwr,c_to_s_ece,c_to_s_urg,c_to_s_ack,c_to_s_psh,c_to_s_rst,c_to_s_syn,c_to_s_fin,"); fprintf(csv_fp, "s_to_c_cwr,s_to_c_ece,s_to_c_urg,s_to_c_ack,s_to_c_psh,s_to_c_rst,s_to_c_syn,s_to_c_fin,"); /* TCP window */ fprintf(csv_fp, "c_to_s_init_win,s_to_c_init_win,"); /* Flow info */ fprintf(csv_fp, "client_info,server_info,"); fprintf(csv_fp, "tls_version,ja3c,tls_client_unsafe,"); fprintf(csv_fp, "ja3s,tls_server_unsafe,"); fprintf(csv_fp, "tls_alpn,tls_supported_versions,"); fprintf(csv_fp, "tls_issuerDN,tls_subjectDN,"); fprintf(csv_fp, "ssh_client_hassh,ssh_server_hassh,flow_info"); /* Joy */ if(enable_joy_stats) { fprintf(csv_fp, ",byte_dist_mean,byte_dist_std,entropy,total_entropy"); } fprintf(csv_fp, "\n"); } /* ********************************** */ /** * @brief Option parser */ static void parseOptions(int argc, char **argv) { int option_idx = 0, do_capture = 0; char *__pcap_file = NULL, *bind_mask = NULL; int thread_id, opt; #ifdef linux u_int num_cores = sysconf(_SC_NPROCESSORS_ONLN); #endif #ifdef DEBUG_TRACE trace = fopen("/tmp/ndpiReader.log", "a"); if(trace) fprintf(trace, " #### %s #### \n", __FUNCTION__); #endif #ifdef USE_DPDK { int ret = rte_eal_init(argc, argv); if(ret < 0) rte_exit(EXIT_FAILURE, "Error with EAL initialization\n"); argc -= ret, argv += ret; } #endif while((opt = getopt_long(argc, argv, "e:c:C:df:g:i:hp:P:l:s:tv:V:n:Jrp:w:q0123:456:7:89:m:T:U:", longopts, &option_idx)) != EOF) { #ifdef DEBUG_TRACE if(trace) fprintf(trace, " #### -%c [%s] #### \n", opt, optarg ? optarg : ""); #endif switch (opt) { case 'd': enable_protocol_guess = 0; break; case 'e': human_readeable_string_len = atoi(optarg); break; case 'i': case '3': _pcap_file[0] = optarg; break; case 'm': pcap_analysis_duration = atol(optarg); break; case 'f': case '6': bpfFilter = optarg; break; case 'g': bind_mask = optarg; break; case 'l': num_loops = atoi(optarg); break; case 'n': num_threads = atoi(optarg); break; case 'p': _protoFilePath = optarg; break; case 'c': _customCategoryFilePath = optarg; break; case 'C': if((csv_fp = fopen(optarg, "w")) == NULL) printf("Unable to write on CSV file %s\n", optarg); break; case 's': capture_for = atoi(optarg); capture_until = capture_for + time(NULL); break; case 't': decode_tunnels = 1; break; case 'r': printf("ndpiReader - nDPI (%s)\n", ndpi_revision()); exit(0); case 'v': verbose = atoi(optarg); break; case 'V': nDPI_LogLevel = atoi(optarg); if(nDPI_LogLevel < 0) nDPI_LogLevel = 0; if(nDPI_LogLevel > 3) { nDPI_LogLevel = 3; _debug_protocols = strdup("all"); } break; case 'h': help(1); break; case 'J': enable_joy_stats = 1; break; case 'P': { int _min_pattern_len, _max_pattern_len, _max_num_packets_per_flow, _max_packet_payload_dissection, _max_num_reported_top_payloads; enable_payload_analyzer = 1; if(sscanf(optarg, "%d:%d:%d:%d:%d", &_min_pattern_len, &_max_pattern_len, &_max_num_packets_per_flow, &_max_packet_payload_dissection, &_max_num_reported_top_payloads) == 5) { min_pattern_len = _min_pattern_len, max_pattern_len = _max_pattern_len; max_num_packets_per_flow = _max_num_packets_per_flow, max_packet_payload_dissection = _max_packet_payload_dissection; max_num_reported_top_payloads = _max_num_reported_top_payloads; if(min_pattern_len > max_pattern_len) min_pattern_len = max_pattern_len; if(min_pattern_len < 2) min_pattern_len = 2; if(max_pattern_len > 16) max_pattern_len = 16; if(max_num_packets_per_flow == 0) max_num_packets_per_flow = 1; if(max_packet_payload_dissection < 4) max_packet_payload_dissection = 4; if(max_num_reported_top_payloads == 0) max_num_reported_top_payloads = 1; } else { printf("Invalid -P format. Ignored\n"); help(0); } } break; case 'w': results_path = strdup(optarg); if((results_file = fopen(results_path, "w")) == NULL) { printf("Unable to write in file %s: quitting\n", results_path); return; } break; case 'q': quiet_mode = 1; nDPI_LogLevel = 0; break; /* Extcap */ case '0': extcap_interfaces(); break; case '1': printf("extcap {version=%s}\n", ndpi_revision()); break; case '2': extcap_dlts(); break; case '4': extcap_config(); break; case '5': do_capture = 1; break; case '7': extcap_capture_fifo = strdup(optarg); break; case '8': nDPI_LogLevel = NDPI_LOG_DEBUG_EXTRA; _debug_protocols = strdup("all"); break; case '9': extcap_packet_filter = ndpi_get_proto_by_name(ndpi_info_mod, optarg); if(extcap_packet_filter == NDPI_PROTOCOL_UNKNOWN) extcap_packet_filter = atoi(optarg); break; case 257: _debug_protocols = strdup(optarg); break; case 'T': max_num_tcp_dissected_pkts = atoi(optarg); if(max_num_tcp_dissected_pkts < 3) max_num_tcp_dissected_pkts = 3; break; case 'U': max_num_udp_dissected_pkts = atoi(optarg); if(max_num_udp_dissected_pkts < 3) max_num_udp_dissected_pkts = 3; break; default: help(0); break; } } if(_pcap_file[0] == NULL) help(0); if(csv_fp) printCSVHeader(); #ifndef USE_DPDK if(strchr(_pcap_file[0], ',')) { /* multiple ingress interfaces */ num_threads = 0; /* setting number of threads = number of interfaces */ __pcap_file = strtok(_pcap_file[0], ","); while(__pcap_file != NULL && num_threads < MAX_NUM_READER_THREADS) { _pcap_file[num_threads++] = __pcap_file; __pcap_file = strtok(NULL, ","); } } else { if(num_threads > MAX_NUM_READER_THREADS) num_threads = MAX_NUM_READER_THREADS; for(thread_id = 1; thread_id < num_threads; thread_id++) _pcap_file[thread_id] = _pcap_file[0]; } #ifdef linux for(thread_id = 0; thread_id < num_threads; thread_id++) core_affinity[thread_id] = -1; if(num_cores > 1 && bind_mask != NULL) { char *core_id = strtok(bind_mask, ":"); thread_id = 0; while(core_id != NULL && thread_id < num_threads) { core_affinity[thread_id++] = atoi(core_id) % num_cores; core_id = strtok(NULL, ":"); } } #endif #endif #ifdef DEBUG_TRACE if(trace) fclose(trace); #endif } /* ********************************** */ /** * @brief From IPPROTO to string NAME */ static char* ipProto2Name(u_int16_t proto_id) { static char proto[8]; switch(proto_id) { case IPPROTO_TCP: return("TCP"); break; case IPPROTO_UDP: return("UDP"); break; case IPPROTO_ICMP: return("ICMP"); break; case IPPROTO_ICMPV6: return("ICMPV6"); break; case 112: return("VRRP"); break; case IPPROTO_IGMP: return("IGMP"); break; } snprintf(proto, sizeof(proto), "%u", proto_id); return(proto); } /* ********************************** */ #if 0 /** * @brief A faster replacement for inet_ntoa(). */ char* intoaV4(u_int32_t addr, char* buf, u_int16_t bufLen) { char *cp; int n; cp = &buf[bufLen]; *--cp = '\0'; n = 4; do { u_int byte = addr & 0xff; *--cp = byte % 10 + '0'; byte /= 10; if(byte > 0) { *--cp = byte % 10 + '0'; byte /= 10; if(byte > 0) *--cp = byte + '0'; } if(n > 1) *--cp = '.'; addr >>= 8; } while (--n > 0); return(cp); } #endif /* ********************************** */ static char* print_cipher(ndpi_cipher_weakness c) { switch(c) { case ndpi_cipher_insecure: return(" (INSECURE)"); break; case ndpi_cipher_weak: return(" (WEAK)"); break; default: return(""); } } /* ********************************** */ static char* is_unsafe_cipher(ndpi_cipher_weakness c) { switch(c) { case ndpi_cipher_insecure: return("INSECURE"); break; case ndpi_cipher_weak: return("WEAK"); break; default: return("OK"); } } /* ********************************** */ /** * @brief Print the flow */ static void printFlow(u_int16_t id, struct ndpi_flow_info *flow, u_int16_t thread_id) { FILE *out = results_file ? results_file : stdout; u_int8_t known_tls; char buf[32], buf1[64]; u_int i; double dos_ge_score; double dos_slow_score; double dos_hulk_score; double ddos_score; double hearthbleed_score; double ftp_patator_score; double ssh_patator_score; double inf_score; if(csv_fp != NULL) { float data_ratio = ndpi_data_ratio(flow->src2dst_bytes, flow->dst2src_bytes); double f = (double)flow->first_seen, l = (double)flow->last_seen; /* PLEASE KEEP IN SYNC WITH printCSVHeader() */ dos_ge_score = Dos_goldeneye_score(flow); dos_slow_score = Dos_slow_score(flow); dos_hulk_score = Dos_hulk_score(flow); ddos_score = Ddos_score(flow); hearthbleed_score = Hearthbleed_score(flow); ftp_patator_score = Ftp_patator_score(flow); ssh_patator_score = Ssh_patator_score(flow); inf_score = Infiltration_score(flow); double benign_score = dos_ge_score < 1 && dos_slow_score < 1 && \ dos_hulk_score < 1 && ddos_score < 1 && hearthbleed_score < 1 && \ ftp_patator_score < 1 && ssh_patator_score < 1 && inf_score < 1 ? 1.1 : 0; fprintf(csv_fp, "%u,%u,%.3f,%.3f,%.3f,%s,%u,%s,%u,", flow->flow_id, flow->protocol, f/1000.0, l/1000.0, (l-f)/1000.0, flow->src_name, ntohs(flow->src_port), flow->dst_name, ntohs(flow->dst_port) ); fprintf(csv_fp, "%s,", ndpi_protocol2id(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol, buf, sizeof(buf))); fprintf(csv_fp, "%s,%s,", ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol, buf, sizeof(buf)), flow->host_server_name); fprintf(csv_fp, "%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,", \ benign_score, dos_slow_score, dos_ge_score, dos_hulk_score, \ ddos_score, hearthbleed_score, ftp_patator_score, \ ssh_patator_score, inf_score); fprintf(csv_fp, "%u,%llu,%llu,", flow->src2dst_packets, (long long unsigned int) flow->src2dst_bytes, (long long unsigned int) flow->src2dst_goodput_bytes); fprintf(csv_fp, "%u,%llu,%llu,", flow->dst2src_packets, (long long unsigned int) flow->dst2src_bytes, (long long unsigned int) flow->dst2src_goodput_bytes); fprintf(csv_fp, "%.3f,%s,", data_ratio, ndpi_data_ratio2str(data_ratio)); fprintf(csv_fp, "%.1f,%.1f,", 100.0*((float)flow->src2dst_goodput_bytes / (float)(flow->src2dst_bytes+1)), 100.0*((float)flow->dst2src_goodput_bytes / (float)(flow->dst2src_bytes+1))); /* IAT (Inter Arrival Time) */ fprintf(csv_fp, "%u,%.1f,%u,%.1f,", ndpi_data_min(flow->iat_flow), ndpi_data_average(flow->iat_flow), ndpi_data_max(flow->iat_flow), ndpi_data_stddev(flow->iat_flow)); fprintf(csv_fp, "%u,%.1f,%u,%.1f,%u,%.1f,%u,%.1f,", ndpi_data_min(flow->iat_c_to_s), ndpi_data_average(flow->iat_c_to_s), ndpi_data_max(flow->iat_c_to_s), ndpi_data_stddev(flow->iat_c_to_s), ndpi_data_min(flow->iat_s_to_c), ndpi_data_average(flow->iat_s_to_c), ndpi_data_max(flow->iat_s_to_c), ndpi_data_stddev(flow->iat_s_to_c)); /* Packet Length */ fprintf(csv_fp, "%u,%.1f,%u,%.1f,%u,%.1f,%u,%.1f,", ndpi_data_min(flow->pktlen_c_to_s), ndpi_data_average(flow->pktlen_c_to_s), ndpi_data_max(flow->pktlen_c_to_s), ndpi_data_stddev(flow->pktlen_c_to_s), ndpi_data_min(flow->pktlen_s_to_c), ndpi_data_average(flow->pktlen_s_to_c), ndpi_data_max(flow->pktlen_s_to_c), ndpi_data_stddev(flow->pktlen_s_to_c)); /* TCP flags */ fprintf(csv_fp, "%d,%d,%d,%d,%d,%d,%d,%d,", flow->cwr_count, flow->ece_count, flow->urg_count, flow->ack_count, flow->psh_count, flow->rst_count, flow->syn_count, flow->fin_count); fprintf(csv_fp, "%d,%d,%d,%d,%d,%d,%d,%d,", flow->src2dst_cwr_count, flow->src2dst_ece_count, flow->src2dst_urg_count, flow->src2dst_ack_count, flow->src2dst_psh_count, flow->src2dst_rst_count, flow->src2dst_syn_count, flow->src2dst_fin_count); fprintf(csv_fp, "%d,%d,%d,%d,%d,%d,%d,%d,", flow->dst2src_cwr_count, flow->ece_count, flow->urg_count, flow->ack_count, flow->psh_count, flow->rst_count, flow->syn_count, flow->fin_count); /* TCP window */ fprintf(csv_fp, "%u,%u,", flow->c_to_s_init_win, flow->s_to_c_init_win); fprintf(csv_fp, "%s,%s,", (flow->ssh_tls.client_requested_server_name[0] != '\0') ? flow->ssh_tls.client_requested_server_name : "", (flow->ssh_tls.server_info[0] != '\0') ? flow->ssh_tls.server_info : ""); fprintf(csv_fp, "%s,%s,%s,%s,%s,", (flow->ssh_tls.ssl_version != 0) ? ndpi_ssl_version2str(flow->ssh_tls.ssl_version, &known_tls) : "0", (flow->ssh_tls.ja3_client[0] != '\0') ? flow->ssh_tls.ja3_client : "", (flow->ssh_tls.ja3_client[0] != '\0') ? is_unsafe_cipher(flow->ssh_tls.client_unsafe_cipher) : "0", (flow->ssh_tls.ja3_server[0] != '\0') ? flow->ssh_tls.ja3_server : "", (flow->ssh_tls.ja3_server[0] != '\0') ? is_unsafe_cipher(flow->ssh_tls.server_unsafe_cipher) : "0"); fprintf(csv_fp, "%s,%s,", flow->ssh_tls.tls_alpn ? flow->ssh_tls.tls_alpn : "", flow->ssh_tls.tls_supported_versions ? flow->ssh_tls.tls_supported_versions : "" ); fprintf(csv_fp, "%s,%s,", flow->ssh_tls.tls_issuerDN ? flow->ssh_tls.tls_issuerDN : "", flow->ssh_tls.tls_subjectDN ? flow->ssh_tls.tls_subjectDN : "" ); fprintf(csv_fp, "%s,%s", (flow->ssh_tls.client_hassh[0] != '\0') ? flow->ssh_tls.client_hassh : "", (flow->ssh_tls.server_hassh[0] != '\0') ? flow->ssh_tls.server_hassh : "" ); fprintf(csv_fp, ",%s", flow->info); } if((verbose != 1) && (verbose != 2)) { if(csv_fp && enable_joy_stats) { flowGetBDMeanandVariance(flow); } if(csv_fp) fprintf(csv_fp, "\n"); return; } if(csv_fp || (verbose > 1)) { #if 1 fprintf(out, "\t%u", id); #else fprintf(out, "\t%u(%u)", id, flow->flow_id); #endif fprintf(out, "\t%s ", ipProto2Name(flow->protocol)); fprintf(out, "%s%s%s:%u %s %s%s%s:%u ", (flow->ip_version == 6) ? "[" : "", flow->src_name, (flow->ip_version == 6) ? "]" : "", ntohs(flow->src_port), flow->bidirectional ? "<->" : "->", (flow->ip_version == 6) ? "[" : "", flow->dst_name, (flow->ip_version == 6) ? "]" : "", ntohs(flow->dst_port) ); if(flow->vlan_id > 0) fprintf(out, "[VLAN: %u]", flow->vlan_id); if(enable_payload_analyzer) fprintf(out, "[flowId: %u]", flow->flow_id); } if(enable_joy_stats) { /* Print entropy values for monitored flows. */ flowGetBDMeanandVariance(flow); fflush(out); fprintf(out, "[score: %.4f]", flow->entropy.score); } if(csv_fp) fprintf(csv_fp, "\n"); fprintf(out, "[proto: "); if(flow->tunnel_type != ndpi_no_tunnel) fprintf(out, "%s:", ndpi_tunnel2str(flow->tunnel_type)); fprintf(out, "%s/%s]", ndpi_protocol2id(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol, buf, sizeof(buf)), ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol, buf1, sizeof(buf1))); if(flow->detected_protocol.category != 0) fprintf(out, "[cat: %s/%u]", ndpi_category_get_name(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol.category), (unsigned int)flow->detected_protocol.category); fprintf(out, "[%u pkts/%llu bytes ", flow->src2dst_packets, (long long unsigned int) flow->src2dst_bytes); fprintf(out, "%s %u pkts/%llu bytes]", (flow->dst2src_packets > 0) ? "<->" : "->", flow->dst2src_packets, (long long unsigned int) flow->dst2src_bytes); fprintf(out, "[Goodput ratio: %.0f/%.0f]", 100.0*((float)flow->src2dst_goodput_bytes / (float)(flow->src2dst_bytes+1)), 100.0*((float)flow->dst2src_goodput_bytes / (float)(flow->dst2src_bytes+1))); if(flow->last_seen > flow->first_seen) fprintf(out, "[%.2f sec]", ((float)(flow->last_seen - flow->first_seen))/(float)1000); else fprintf(out, "[< 1 sec]"); if(flow->telnet.username[0] != '\0') fprintf(out, "[Username: %s]", flow->telnet.username); if(flow->telnet.password[0] != '\0') fprintf(out, "[Password: %s]", flow->telnet.password); if(flow->host_server_name[0] != '\0') fprintf(out, "[Host: %s]", flow->host_server_name); if(flow->info[0] != '\0') fprintf(out, "[%s]", flow->info); if(flow->flow_extra_info[0] != '\0') fprintf(out, "[%s]", flow->flow_extra_info); if((flow->src2dst_packets+flow->dst2src_packets) > 5) { if(flow->iat_c_to_s && flow->iat_s_to_c) { float data_ratio = ndpi_data_ratio(flow->src2dst_bytes, flow->dst2src_bytes); fprintf(out, "[bytes ratio: %.3f (%s)]", data_ratio, ndpi_data_ratio2str(data_ratio)); /* IAT (Inter Arrival Time) */ fprintf(out, "[IAT c2s/s2c min/avg/max/stddev: %u/%u %.0f/%.0f %u/%u %.0f/%.0f]", ndpi_data_min(flow->iat_c_to_s), ndpi_data_min(flow->iat_s_to_c), (float)ndpi_data_average(flow->iat_c_to_s), (float)ndpi_data_average(flow->iat_s_to_c), ndpi_data_max(flow->iat_c_to_s), ndpi_data_max(flow->iat_s_to_c), (float)ndpi_data_stddev(flow->iat_c_to_s), (float)ndpi_data_stddev(flow->iat_s_to_c)); /* Packet Length */ fprintf(out, "[Pkt Len c2s/s2c min/avg/max/stddev: %u/%u %.0f/%.0f %u/%u %.0f/%.0f]", ndpi_data_min(flow->pktlen_c_to_s), ndpi_data_min(flow->pktlen_s_to_c), ndpi_data_average(flow->pktlen_c_to_s), ndpi_data_average(flow->pktlen_s_to_c), ndpi_data_max(flow->pktlen_c_to_s), ndpi_data_max(flow->pktlen_s_to_c), ndpi_data_stddev(flow->pktlen_c_to_s), ndpi_data_stddev(flow->pktlen_s_to_c)); } } if(flow->http.url[0] != '\0') { ndpi_risk_enum risk = ndpi_validate_url(flow->http.url); if(risk != NDPI_NO_RISK) NDPI_SET_BIT(flow->risk, risk); fprintf(out, "[URL: %s][StatusCode: %u]", flow->http.url, flow->http.response_status_code); if(flow->http.content_type[0] != '\0') fprintf(out, "[Content-Type: %s]", flow->http.content_type); if(flow->http.user_agent[0] != '\0') fprintf(out, "[User-Agent: %s]", flow->http.user_agent); } if(flow->risk) { u_int i; fprintf(out, "[Risk: "); for(i=0; i<NDPI_MAX_RISK; i++) if(NDPI_ISSET_BIT(flow->risk, i)) fprintf(out, "** %s **", ndpi_risk2str(i)); fprintf(out, "]"); } if(flow->ssh_tls.ssl_version != 0) fprintf(out, "[%s]", ndpi_ssl_version2str(flow->ssh_tls.ssl_version, &known_tls)); if(flow->ssh_tls.client_requested_server_name[0] != '\0') fprintf(out, "[Client: %s]", flow->ssh_tls.client_requested_server_name); if(flow->ssh_tls.client_hassh[0] != '\0') fprintf(out, "[HASSH-C: %s]", flow->ssh_tls.client_hassh); if(flow->ssh_tls.ja3_client[0] != '\0') fprintf(out, "[JA3C: %s%s]", flow->ssh_tls.ja3_client, print_cipher(flow->ssh_tls.client_unsafe_cipher)); if(flow->ssh_tls.server_info[0] != '\0') fprintf(out, "[Server: %s]", flow->ssh_tls.server_info); if(flow->ssh_tls.server_names) fprintf(out, "[ServerNames: %s]", flow->ssh_tls.server_names); if(flow->ssh_tls.server_hassh[0] != '\0') fprintf(out, "[HASSH-S: %s]", flow->ssh_tls.server_hassh); if(flow->ssh_tls.ja3_server[0] != '\0') fprintf(out, "[JA3S: %s%s]", flow->ssh_tls.ja3_server, print_cipher(flow->ssh_tls.server_unsafe_cipher)); if(flow->ssh_tls.tls_issuerDN) fprintf(out, "[Issuer: %s]", flow->ssh_tls.tls_issuerDN); if(flow->ssh_tls.tls_subjectDN) fprintf(out, "[Subject: %s]", flow->ssh_tls.tls_subjectDN); if((flow->detected_protocol.master_protocol == NDPI_PROTOCOL_TLS) || (flow->detected_protocol.app_protocol == NDPI_PROTOCOL_TLS)) { if(flow->ssh_tls.sha1_cert_fingerprint_set) { fprintf(out, "[Certificate SHA-1: "); for(i=0; i<20; i++) fprintf(out, "%s%02X", (i > 0) ? ":" : "", flow->ssh_tls.sha1_cert_fingerprint[i] & 0xFF); fprintf(out, "]"); } } if(flow->ssh_tls.notBefore && flow->ssh_tls.notAfter) { char notBefore[32], notAfter[32]; struct tm a, b; struct tm *before = gmtime_r(&flow->ssh_tls.notBefore, &a); struct tm *after = gmtime_r(&flow->ssh_tls.notAfter, &b); strftime(notBefore, sizeof(notBefore), "%F %T", before); strftime(notAfter, sizeof(notAfter), "%F %T", after); fprintf(out, "[Validity: %s - %s]", notBefore, notAfter); } if(flow->ssh_tls.server_cipher != '\0') fprintf(out, "[Cipher: %s]", ndpi_cipher2str(flow->ssh_tls.server_cipher)); if(flow->bittorent_hash[0] != '\0') fprintf(out, "[BT Hash: %s]", flow->bittorent_hash); if(flow->dhcp_fingerprint[0] != '\0') fprintf(out, "[DHCP Fingerprint: %s]", flow->dhcp_fingerprint); if(flow->has_human_readeable_strings) fprintf(out, "[PLAIN TEXT (%s)]", flow->human_readeable_string_buffer); fprintf(out, "\n"); } /* ********************************** */ /** * @brief Unknown Proto Walker */ static void node_print_unknown_proto_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) { struct ndpi_flow_info *flow = *(struct ndpi_flow_info**)node; u_int16_t thread_id = *((u_int16_t*)user_data); if((flow->detected_protocol.master_protocol != NDPI_PROTOCOL_UNKNOWN) || (flow->detected_protocol.app_protocol != NDPI_PROTOCOL_UNKNOWN)) return; if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */ all_flows[num_flows].thread_id = thread_id, all_flows[num_flows].flow = flow; num_flows++; } } /* ********************************** */ /** * @brief Known Proto Walker */ static void node_print_known_proto_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) { struct ndpi_flow_info *flow = *(struct ndpi_flow_info**)node; u_int16_t thread_id = *((u_int16_t*)user_data); if((flow->detected_protocol.master_protocol == NDPI_PROTOCOL_UNKNOWN) && (flow->detected_protocol.app_protocol == NDPI_PROTOCOL_UNKNOWN)) return; if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */ all_flows[num_flows].thread_id = thread_id, all_flows[num_flows].flow = flow; num_flows++; } } /* ********************************** */ /** * @brief Proto Guess Walker */ static void node_proto_guess_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) { struct ndpi_flow_info *flow = *(struct ndpi_flow_info **) node; u_int16_t thread_id = *((u_int16_t *) user_data), proto; if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */ if((!flow->detection_completed) && flow->ndpi_flow) { u_int8_t proto_guessed; flow->detected_protocol = ndpi_detection_giveup(ndpi_thread_info[0].workflow->ndpi_struct, flow->ndpi_flow, enable_protocol_guess, &proto_guessed); } process_ndpi_collected_info(ndpi_thread_info[thread_id].workflow, flow); proto = flow->detected_protocol.app_protocol ? flow->detected_protocol.app_protocol : flow->detected_protocol.master_protocol; ndpi_thread_info[thread_id].workflow->stats.protocol_counter[proto] += flow->src2dst_packets + flow->dst2src_packets; ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes[proto] += flow->src2dst_bytes + flow->dst2src_bytes; ndpi_thread_info[thread_id].workflow->stats.protocol_flows[proto]++; } } /* *********************************************** */ void updateScanners(struct single_flow_info **scanners, u_int32_t saddr, u_int8_t version, u_int32_t dport) { struct single_flow_info *f; struct port_flow_info *p; HASH_FIND_INT(*scanners, (int *)&saddr, f); if(f == NULL) { f = (struct single_flow_info*)malloc(sizeof(struct single_flow_info)); if(!f) return; f->saddr = saddr; f->version = version; f->tot_flows = 1; f->ports = NULL; p = (struct port_flow_info*)malloc(sizeof(struct port_flow_info)); if(!p) { free(f); return; } else p->port = dport, p->num_flows = 1; HASH_ADD_INT(f->ports, port, p); HASH_ADD_INT(*scanners, saddr, f); } else{ struct port_flow_info *pp; f->tot_flows++; HASH_FIND_INT(f->ports, (int *)&dport, pp); if(pp == NULL) { pp = (struct port_flow_info*)malloc(sizeof(struct port_flow_info)); if(!pp) return; pp->port = dport, pp->num_flows = 1; HASH_ADD_INT(f->ports, port, pp); } else pp->num_flows++; } } /* *********************************************** */ int updateIpTree(u_int32_t key, u_int8_t version, addr_node **vrootp, const char *proto) { addr_node *q; addr_node **rootp = vrootp; if(rootp == (addr_node **)0) return 0; while(*rootp != (addr_node *)0) { /* Knuth's T1: */ if((version == (*rootp)->version) && (key == (*rootp)->addr)) { /* T2: */ return ++((*rootp)->count); } rootp = (key < (*rootp)->addr) ? &(*rootp)->left : /* T3: follow left branch */ &(*rootp)->right; /* T4: follow right branch */ } q = (addr_node *) malloc(sizeof(addr_node)); /* T5: key not found */ if(q != (addr_node *)0) { /* make new node */ *rootp = q; /* link new node to old */ q->addr = key; q->version = version; strncpy(q->proto, proto, sizeof(q->proto)); q->count = UPDATED_TREE; q->left = q->right = (addr_node *)0; return q->count; } return(0); } /* *********************************************** */ void freeIpTree(addr_node *root) { if(root == NULL) return; freeIpTree(root->left); freeIpTree(root->right); free(root); } /* *********************************************** */ void updateTopIpAddress(u_int32_t addr, u_int8_t version, const char *proto, int count, struct info_pair top[], int size) { struct info_pair pair; int min = count; int update = 0; int min_i = 0; int i; if(count == 0) return; pair.addr = addr; pair.version = version; pair.count = count; strncpy(pair.proto, proto, sizeof(pair.proto)); for(i=0; i<size; i++) { /* if the same ip with a bigger count just update it */ if(top[i].addr == addr) { top[i].count = count; return; } /* if array is not full yet add it to the first empty place */ if(top[i].count == 0) { top[i] = pair; return; } } /* if bigger than the smallest one, replace it */ for(i=0; i<size; i++) { if(top[i].count < count && top[i].count < min) { min = top[i].count; min_i = i; update = 1; } } if(update) top[min_i] = pair; } /* *********************************************** */ static void updatePortStats(struct port_stats **stats, u_int32_t port, u_int32_t addr, u_int8_t version, u_int32_t num_pkts, u_int32_t num_bytes, const char *proto) { struct port_stats *s = NULL; int count = 0; HASH_FIND_INT(*stats, &port, s); if(s == NULL) { s = (struct port_stats*)calloc(1, sizeof(struct port_stats)); if(!s) return; s->port = port, s->num_pkts = num_pkts, s->num_bytes = num_bytes; s->num_addr = 1, s->cumulative_addr = 1; s->num_flows = 1; updateTopIpAddress(addr, version, proto, 1, s->top_ip_addrs, MAX_NUM_IP_ADDRESS); s->addr_tree = (addr_node *) malloc(sizeof(addr_node)); if(!s->addr_tree) { free(s); return; } s->addr_tree->addr = addr; s->addr_tree->version = version; strncpy(s->addr_tree->proto, proto, sizeof(s->addr_tree->proto)); s->addr_tree->count = 1; s->addr_tree->left = NULL; s->addr_tree->right = NULL; HASH_ADD_INT(*stats, port, s); } else{ count = updateIpTree(addr, version, &(*s).addr_tree, proto); if(count == UPDATED_TREE) s->num_addr++; if(count) { s->cumulative_addr++; updateTopIpAddress(addr, version, proto, count, s->top_ip_addrs, MAX_NUM_IP_ADDRESS); } s->num_pkts += num_pkts, s->num_bytes += num_bytes, s->num_flows++; } } /* *********************************************** */ /* @brief heuristic choice for receiver stats */ static int acceptable(u_int32_t num_pkts){ return num_pkts > 5; } /* *********************************************** */ #if 0 static int receivers_sort(void *_a, void *_b) { struct receiver *a = (struct receiver *)_a; struct receiver *b = (struct receiver *)_b; return(b->num_pkts - a->num_pkts); } #endif /* *********************************************** */ static int receivers_sort_asc(void *_a, void *_b) { struct receiver *a = (struct receiver *)_a; struct receiver *b = (struct receiver *)_b; return(a->num_pkts - b->num_pkts); } /* ***************************************************** */ /*@brief removes first (size - max) elements from hash table. * hash table is ordered in ascending order. */ static struct receiver *cutBackTo(struct receiver **rcvrs, u_int32_t size, u_int32_t max) { struct receiver *r, *tmp; int i=0; int count; if(size < max) //return the original table return *rcvrs; count = size - max; HASH_ITER(hh, *rcvrs, r, tmp) { if(i++ == count) return r; HASH_DEL(*rcvrs, r); free(r); } return(NULL); } /* *********************************************** */ /*@brief merge first table to the second table. * if element already in the second table * then updates its value * else adds it to the second table */ static void mergeTables(struct receiver **primary, struct receiver **secondary) { struct receiver *r, *s, *tmp; HASH_ITER(hh, *primary, r, tmp) { HASH_FIND_INT(*secondary, (int *)&(r->addr), s); if(s == NULL){ s = (struct receiver *)malloc(sizeof(struct receiver)); if(!s) return; s->addr = r->addr; s->version = r->version; s->num_pkts = r->num_pkts; HASH_ADD_INT(*secondary, addr, s); } else s->num_pkts += r->num_pkts; HASH_DEL(*primary, r); free(r); } } /* *********************************************** */ static void deleteReceivers(struct receiver *rcvrs) { struct receiver *current, *tmp; HASH_ITER(hh, rcvrs, current, tmp) { HASH_DEL(rcvrs, current); free(current); } } /* *********************************************** */ /* implementation of: https://jeroen.massar.ch/presentations/files/FloCon2010-TopK.pdf * * if(table1.size < max1 || acceptable){ * create new element and add to the table1 * if(table1.size > max2) { * cut table1 back to max1 * merge table 1 to table2 * if(table2.size > max1) * cut table2 back to max1 * } * } * else * update table1 */ static void updateReceivers(struct receiver **rcvrs, u_int32_t dst_addr, u_int8_t version, u_int32_t num_pkts, struct receiver **topRcvrs) { struct receiver *r; u_int32_t size; int a; HASH_FIND_INT(*rcvrs, (int *)&dst_addr, r); if(r == NULL) { if(((size = HASH_COUNT(*rcvrs)) < MAX_TABLE_SIZE_1) || ((a = acceptable(num_pkts)) != 0)){ r = (struct receiver *)malloc(sizeof(struct receiver)); if(!r) return; r->addr = dst_addr; r->version = version; r->num_pkts = num_pkts; HASH_ADD_INT(*rcvrs, addr, r); if((size = HASH_COUNT(*rcvrs)) > MAX_TABLE_SIZE_2){ HASH_SORT(*rcvrs, receivers_sort_asc); *rcvrs = cutBackTo(rcvrs, size, MAX_TABLE_SIZE_1); mergeTables(rcvrs, topRcvrs); if((size = HASH_COUNT(*topRcvrs)) > MAX_TABLE_SIZE_1){ HASH_SORT(*topRcvrs, receivers_sort_asc); *topRcvrs = cutBackTo(topRcvrs, size, MAX_TABLE_SIZE_1); } *rcvrs = NULL; } } } else r->num_pkts += num_pkts; } /* *********************************************** */ static void deleteScanners(struct single_flow_info *scanners) { struct single_flow_info *s, *tmp; struct port_flow_info *p, *tmp2; HASH_ITER(hh, scanners, s, tmp) { HASH_ITER(hh, s->ports, p, tmp2) { if(s->ports) HASH_DEL(s->ports, p); free(p); } HASH_DEL(scanners, s); free(s); } } /* *********************************************** */ static void deletePortsStats(struct port_stats *stats) { struct port_stats *current_port, *tmp; HASH_ITER(hh, stats, current_port, tmp) { HASH_DEL(stats, current_port); freeIpTree(current_port->addr_tree); free(current_port); } } /* *********************************************** */ /** * @brief Ports stats */ static void port_stats_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) { if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */ struct ndpi_flow_info *flow = *(struct ndpi_flow_info **) node; u_int16_t thread_id = *(int *)user_data; u_int16_t sport, dport; char proto[16]; int r; sport = ntohs(flow->src_port), dport = ntohs(flow->dst_port); /* get app level protocol */ if(flow->detected_protocol.master_protocol) ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol, proto, sizeof(proto)); else strncpy(proto, ndpi_get_proto_name(ndpi_thread_info[thread_id].workflow->ndpi_struct, flow->detected_protocol.app_protocol),sizeof(proto)); if(((r = strcmp(ipProto2Name(flow->protocol), "TCP")) == 0) && (flow->src2dst_packets == 1) && (flow->dst2src_packets == 0)) { updateScanners(&scannerHosts, flow->src_ip, flow->ip_version, dport); } updateReceivers(&receivers, flow->dst_ip, flow->ip_version, flow->src2dst_packets, &topReceivers); updatePortStats(&srcStats, sport, flow->src_ip, flow->ip_version, flow->src2dst_packets, flow->src2dst_bytes, proto); updatePortStats(&dstStats, dport, flow->dst_ip, flow->ip_version, flow->dst2src_packets, flow->dst2src_bytes, proto); } } /* *********************************************** */ /** * @brief Idle Scan Walker */ static void node_idle_scan_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) { struct ndpi_flow_info *flow = *(struct ndpi_flow_info **) node; u_int16_t thread_id = *((u_int16_t *) user_data); if(ndpi_thread_info[thread_id].num_idle_flows == IDLE_SCAN_BUDGET) /* TODO optimise with a budget-based walk */ return; if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */ if(flow->last_seen + MAX_IDLE_TIME < ndpi_thread_info[thread_id].workflow->last_time) { /* update stats */ node_proto_guess_walker(node, which, depth, user_data); if((flow->detected_protocol.app_protocol == NDPI_PROTOCOL_UNKNOWN) && !undetected_flows_deleted) undetected_flows_deleted = 1; ndpi_free_flow_info_half(flow); ndpi_free_flow_data_analysis(flow); ndpi_free_flow_tls_data(flow); ndpi_thread_info[thread_id].workflow->stats.ndpi_flow_count--; /* adding to a queue (we can't delete it from the tree inline ) */ ndpi_thread_info[thread_id].idle_flows[ndpi_thread_info[thread_id].num_idle_flows++] = flow; } } } /* *********************************************** */ /** * @brief On Protocol Discover - demo callback */ static void on_protocol_discovered(struct ndpi_workflow * workflow, struct ndpi_flow_info * flow, void * udata) { ; } /* *********************************************** */ #if 0 /** * @brief Print debug */ static void debug_printf(u_int32_t protocol, void *id_struct, ndpi_log_level_t log_level, const char *format, ...) { va_list va_ap; struct tm result; if(log_level <= nDPI_LogLevel) { char buf[8192], out_buf[8192]; char theDate[32]; const char *extra_msg = ""; time_t theTime = time(NULL); va_start (va_ap, format); if(log_level == NDPI_LOG_ERROR) extra_msg = "ERROR: "; else if(log_level == NDPI_LOG_TRACE) extra_msg = "TRACE: "; else extra_msg = "DEBUG: "; memset(buf, 0, sizeof(buf)); strftime(theDate, 32, "%d/%b/%Y %H:%M:%S", localtime_r(&theTime,&result)); vsnprintf(buf, sizeof(buf)-1, format, va_ap); snprintf(out_buf, sizeof(out_buf), "%s %s%s", theDate, extra_msg, buf); printf("%s", out_buf); fflush(stdout); } va_end(va_ap); } #endif /* *********************************************** */ /** * @brief Setup for detection begin */ static void setupDetection(u_int16_t thread_id, pcap_t * pcap_handle) { NDPI_PROTOCOL_BITMASK all; struct ndpi_workflow_prefs prefs; memset(&prefs, 0, sizeof(prefs)); prefs.decode_tunnels = decode_tunnels; prefs.num_roots = NUM_ROOTS; prefs.max_ndpi_flows = MAX_NDPI_FLOWS; prefs.quiet_mode = quiet_mode; memset(&ndpi_thread_info[thread_id], 0, sizeof(ndpi_thread_info[thread_id])); ndpi_thread_info[thread_id].workflow = ndpi_workflow_init(&prefs, pcap_handle); /* Preferences */ ndpi_workflow_set_flow_detected_callback(ndpi_thread_info[thread_id].workflow, on_protocol_discovered, (void *)(uintptr_t)thread_id); // enable all protocols NDPI_BITMASK_SET_ALL(all); ndpi_set_protocol_detection_bitmask2(ndpi_thread_info[thread_id].workflow->ndpi_struct, &all); // clear memory for results memset(ndpi_thread_info[thread_id].workflow->stats.protocol_counter, 0, sizeof(ndpi_thread_info[thread_id].workflow->stats.protocol_counter)); memset(ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes, 0, sizeof(ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes)); memset(ndpi_thread_info[thread_id].workflow->stats.protocol_flows, 0, sizeof(ndpi_thread_info[thread_id].workflow->stats.protocol_flows)); if(_protoFilePath != NULL) ndpi_load_protocols_file(ndpi_thread_info[thread_id].workflow->ndpi_struct, _protoFilePath); if(_customCategoryFilePath) ndpi_load_categories_file(ndpi_thread_info[thread_id].workflow->ndpi_struct, _customCategoryFilePath); ndpi_finalize_initalization(ndpi_thread_info[thread_id].workflow->ndpi_struct); } /* *********************************************** */ /** * @brief End of detection and free flow */ static void terminateDetection(u_int16_t thread_id) { ndpi_workflow_free(ndpi_thread_info[thread_id].workflow); } /* *********************************************** */ /** * @brief Traffic stats format */ char* formatTraffic(float numBits, int bits, char *buf) { char unit; if(bits) unit = 'b'; else unit = 'B'; if(numBits < 1024) { snprintf(buf, 32, "%lu %c", (unsigned long)numBits, unit); } else if(numBits < (1024*1024)) { snprintf(buf, 32, "%.2f K%c", (float)(numBits)/1024, unit); } else { float tmpMBits = ((float)numBits)/(1024*1024); if(tmpMBits < 1024) { snprintf(buf, 32, "%.2f M%c", tmpMBits, unit); } else { tmpMBits /= 1024; if(tmpMBits < 1024) { snprintf(buf, 32, "%.2f G%c", tmpMBits, unit); } else { snprintf(buf, 32, "%.2f T%c", (float)(tmpMBits)/1024, unit); } } } return(buf); } /* *********************************************** */ /** * @brief Packets stats format */ char* formatPackets(float numPkts, char *buf) { if(numPkts < 1000) { snprintf(buf, 32, "%.2f", numPkts); } else if(numPkts < (1000*1000)) { snprintf(buf, 32, "%.2f K", numPkts/1000); } else { numPkts /= (1000*1000); snprintf(buf, 32, "%.2f M", numPkts); } return(buf); } /* *********************************************** */ /** * @brief Bytes stats format */ char* formatBytes(u_int32_t howMuch, char *buf, u_int buf_len) { char unit = 'B'; if(howMuch < 1024) { snprintf(buf, buf_len, "%lu %c", (unsigned long)howMuch, unit); } else if(howMuch < (1024*1024)) { snprintf(buf, buf_len, "%.2f K%c", (float)(howMuch)/1024, unit); } else { float tmpGB = ((float)howMuch)/(1024*1024); if(tmpGB < 1024) { snprintf(buf, buf_len, "%.2f M%c", tmpGB, unit); } else { tmpGB /= 1024; snprintf(buf, buf_len, "%.2f G%c", tmpGB, unit); } } return(buf); } /* *********************************************** */ static int port_stats_sort(void *_a, void *_b) { struct port_stats *a = (struct port_stats*)_a; struct port_stats *b = (struct port_stats*)_b; if(b->num_pkts == 0 && a->num_pkts == 0) return(b->num_flows - a->num_flows); return(b->num_pkts - a->num_pkts); } /* *********************************************** */ static int info_pair_cmp (const void *_a, const void *_b) { struct info_pair *a = (struct info_pair *)_a; struct info_pair *b = (struct info_pair *)_b; return b->count - a->count; } /* *********************************************** */ void printPortStats(struct port_stats *stats) { struct port_stats *s, *tmp; char addr_name[48]; int i = 0, j = 0; HASH_ITER(hh, stats, s, tmp) { i++; printf("\t%2d\tPort %5u\t[%u IP address(es)/%u flows/%u pkts/%u bytes]\n\t\tTop IP Stats:\n", i, s->port, s->num_addr, s->num_flows, s->num_pkts, s->num_bytes); qsort(&s->top_ip_addrs[0], MAX_NUM_IP_ADDRESS, sizeof(struct info_pair), info_pair_cmp); for(j=0; j<MAX_NUM_IP_ADDRESS; j++) { if(s->top_ip_addrs[j].count != 0) { if(s->top_ip_addrs[j].version == IPVERSION) { inet_ntop(AF_INET, &(s->top_ip_addrs[j].addr), addr_name, sizeof(addr_name)); } else { inet_ntop(AF_INET6, &(s->top_ip_addrs[j].addr), addr_name, sizeof(addr_name)); } printf("\t\t%-36s ~ %.2f%%\n", addr_name, ((s->top_ip_addrs[j].count) * 100.0) / s->cumulative_addr); } } printf("\n"); if(i >= 10) break; } } /* *********************************************** */ static void printFlowsStats() { int thread_id; u_int32_t total_flows = 0; FILE *out = results_file ? results_file : stdout; if(enable_payload_analyzer) ndpi_report_payload_stats(); for(thread_id = 0; thread_id < num_threads; thread_id++) total_flows += ndpi_thread_info[thread_id].workflow->num_allocated_flows; if((all_flows = (struct flow_info*)malloc(sizeof(struct flow_info)*total_flows)) == NULL) { fprintf(out, "Fatal error: not enough memory\n"); exit(-1); } if(verbose) { ndpi_host_ja3_fingerprints *ja3ByHostsHashT = NULL; // outer hash table ndpi_ja3_fingerprints_host *hostByJA3C_ht = NULL; // for client ndpi_ja3_fingerprints_host *hostByJA3S_ht = NULL; // for server int i; ndpi_host_ja3_fingerprints *ja3ByHost_element = NULL; ndpi_ja3_info *info_of_element = NULL; ndpi_host_ja3_fingerprints *tmp = NULL; ndpi_ja3_info *tmp2 = NULL; unsigned int num_ja3_client; unsigned int num_ja3_server; fprintf(out, "\n"); num_flows = 0; for(thread_id = 0; thread_id < num_threads; thread_id++) { for(i=0; i<NUM_ROOTS; i++) ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], node_print_known_proto_walker, &thread_id); } if((verbose == 2) || (verbose == 3)) { for(i = 0; i < num_flows; i++) { ndpi_host_ja3_fingerprints *ja3ByHostFound = NULL; ndpi_ja3_fingerprints_host *hostByJA3Found = NULL; //check if this is a ssh-ssl flow if(all_flows[i].flow->ssh_tls.ja3_client[0] != '\0'){ //looking if the host is already in the hash table HASH_FIND_INT(ja3ByHostsHashT, &(all_flows[i].flow->src_ip), ja3ByHostFound); //host ip -> ja3 if(ja3ByHostFound == NULL){ //adding the new host ndpi_host_ja3_fingerprints *newHost = malloc(sizeof(ndpi_host_ja3_fingerprints)); newHost->host_client_info_hasht = NULL; newHost->host_server_info_hasht = NULL; newHost->ip_string = all_flows[i].flow->src_name; newHost->ip = all_flows[i].flow->src_ip; newHost->dns_name = all_flows[i].flow->ssh_tls.client_requested_server_name; ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info)); newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_client; newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.client_unsafe_cipher; //adding the new ja3 fingerprint HASH_ADD_KEYPTR(hh, newHost->host_client_info_hasht, newJA3->ja3, strlen(newJA3->ja3), newJA3); //adding the new host HASH_ADD_INT(ja3ByHostsHashT, ip, newHost); } else { //host already in the hash table ndpi_ja3_info *infoFound = NULL; HASH_FIND_STR(ja3ByHostFound->host_client_info_hasht, all_flows[i].flow->ssh_tls.ja3_client, infoFound); if(infoFound == NULL){ ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info)); newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_client; newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.client_unsafe_cipher; HASH_ADD_KEYPTR(hh, ja3ByHostFound->host_client_info_hasht, newJA3->ja3, strlen(newJA3->ja3), newJA3); } } //ja3 -> host ip HASH_FIND_STR(hostByJA3C_ht, all_flows[i].flow->ssh_tls.ja3_client, hostByJA3Found); if(hostByJA3Found == NULL){ ndpi_ip_dns *newHost = malloc(sizeof(ndpi_ip_dns)); newHost->ip = all_flows[i].flow->src_ip; newHost->ip_string = all_flows[i].flow->src_name; newHost->dns_name = all_flows[i].flow->ssh_tls.client_requested_server_name;; ndpi_ja3_fingerprints_host *newElement = malloc(sizeof(ndpi_ja3_fingerprints_host)); newElement->ja3 = all_flows[i].flow->ssh_tls.ja3_client; newElement->unsafe_cipher = all_flows[i].flow->ssh_tls.client_unsafe_cipher; newElement->ipToDNS_ht = NULL; HASH_ADD_INT(newElement->ipToDNS_ht, ip, newHost); HASH_ADD_KEYPTR(hh, hostByJA3C_ht, newElement->ja3, strlen(newElement->ja3), newElement); } else { ndpi_ip_dns *innerElement = NULL; HASH_FIND_INT(hostByJA3Found->ipToDNS_ht, &(all_flows[i].flow->src_ip), innerElement); if(innerElement == NULL){ ndpi_ip_dns *newInnerElement = malloc(sizeof(ndpi_ip_dns)); newInnerElement->ip = all_flows[i].flow->src_ip; newInnerElement->ip_string = all_flows[i].flow->src_name; newInnerElement->dns_name = all_flows[i].flow->ssh_tls.client_requested_server_name; HASH_ADD_INT(hostByJA3Found->ipToDNS_ht, ip, newInnerElement); } } } if(all_flows[i].flow->ssh_tls.ja3_server[0] != '\0'){ //looking if the host is already in the hash table HASH_FIND_INT(ja3ByHostsHashT, &(all_flows[i].flow->dst_ip), ja3ByHostFound); if(ja3ByHostFound == NULL){ //adding the new host in the hash table ndpi_host_ja3_fingerprints *newHost = malloc(sizeof(ndpi_host_ja3_fingerprints)); newHost->host_client_info_hasht = NULL; newHost->host_server_info_hasht = NULL; newHost->ip_string = all_flows[i].flow->dst_name; newHost->ip = all_flows[i].flow->dst_ip; newHost->dns_name = all_flows[i].flow->ssh_tls.server_info; ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info)); newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_server; newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.server_unsafe_cipher; //adding the new ja3 fingerprint HASH_ADD_KEYPTR(hh, newHost->host_server_info_hasht, newJA3->ja3, strlen(newJA3->ja3), newJA3); //adding the new host HASH_ADD_INT(ja3ByHostsHashT, ip, newHost); } else { //host already in the hashtable ndpi_ja3_info *infoFound = NULL; HASH_FIND_STR(ja3ByHostFound->host_server_info_hasht, all_flows[i].flow->ssh_tls.ja3_server, infoFound); if(infoFound == NULL){ ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info)); newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_server; newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.server_unsafe_cipher; HASH_ADD_KEYPTR(hh, ja3ByHostFound->host_server_info_hasht, newJA3->ja3, strlen(newJA3->ja3), newJA3); } } HASH_FIND_STR(hostByJA3S_ht, all_flows[i].flow->ssh_tls.ja3_server, hostByJA3Found); if(hostByJA3Found == NULL){ ndpi_ip_dns *newHost = malloc(sizeof(ndpi_ip_dns)); newHost->ip = all_flows[i].flow->dst_ip; newHost->ip_string = all_flows[i].flow->dst_name; newHost->dns_name = all_flows[i].flow->ssh_tls.server_info;; ndpi_ja3_fingerprints_host *newElement = malloc(sizeof(ndpi_ja3_fingerprints_host)); newElement->ja3 = all_flows[i].flow->ssh_tls.ja3_server; newElement->unsafe_cipher = all_flows[i].flow->ssh_tls.server_unsafe_cipher; newElement->ipToDNS_ht = NULL; HASH_ADD_INT(newElement->ipToDNS_ht, ip, newHost); HASH_ADD_KEYPTR(hh, hostByJA3S_ht, newElement->ja3, strlen(newElement->ja3), newElement); } else { ndpi_ip_dns *innerElement = NULL; HASH_FIND_INT(hostByJA3Found->ipToDNS_ht, &(all_flows[i].flow->dst_ip), innerElement); if(innerElement == NULL){ ndpi_ip_dns *newInnerElement = malloc(sizeof(ndpi_ip_dns)); newInnerElement->ip = all_flows[i].flow->dst_ip; newInnerElement->ip_string = all_flows[i].flow->dst_name; newInnerElement->dns_name = all_flows[i].flow->ssh_tls.server_info; HASH_ADD_INT(hostByJA3Found->ipToDNS_ht, ip, newInnerElement); } } } } if(ja3ByHostsHashT) { ndpi_ja3_fingerprints_host *hostByJA3Element = NULL; ndpi_ja3_fingerprints_host *tmp3 = NULL; ndpi_ip_dns *innerHashEl = NULL; ndpi_ip_dns *tmp4 = NULL; if(verbose == 2) { /* for each host the number of flow with a ja3 fingerprint is printed */ i = 1; fprintf(out, "JA3 Host Stats: \n"); fprintf(out, "\t\t IP %-24s \t %-10s \n", "Address", "# JA3C"); for(ja3ByHost_element = ja3ByHostsHashT; ja3ByHost_element != NULL; ja3ByHost_element = ja3ByHost_element->hh.next) { num_ja3_client = HASH_COUNT(ja3ByHost_element->host_client_info_hasht); num_ja3_server = HASH_COUNT(ja3ByHost_element->host_server_info_hasht); if(num_ja3_client > 0) { fprintf(out, "\t%d\t %-24s \t %-7u\n", i, ja3ByHost_element->ip_string, num_ja3_client ); i++; } } } else if(verbose == 3) { int i = 1; int againstRepeat; ndpi_ja3_fingerprints_host *hostByJA3Element = NULL; ndpi_ja3_fingerprints_host *tmp3 = NULL; ndpi_ip_dns *innerHashEl = NULL; ndpi_ip_dns *tmp4 = NULL; //for each host it is printted the JA3C and JA3S, along the server name (if any) //and the security status fprintf(out, "JA3C/JA3S Host Stats: \n"); fprintf(out, "\t%-7s %-24s %-34s %s\n", "", "IP", "JA3C", "JA3S"); //reminder //ja3ByHostsHashT: hash table <ip, (ja3, ht_client, ht_server)> //ja3ByHost_element: element of ja3ByHostsHashT //info_of_element: element of the inner hash table of ja3ByHost_element HASH_ITER(hh, ja3ByHostsHashT, ja3ByHost_element, tmp) { num_ja3_client = HASH_COUNT(ja3ByHost_element->host_client_info_hasht); num_ja3_server = HASH_COUNT(ja3ByHost_element->host_server_info_hasht); againstRepeat = 0; if(num_ja3_client > 0) { HASH_ITER(hh, ja3ByHost_element->host_client_info_hasht, info_of_element, tmp2) { fprintf(out, "\t%-7d %-24s %s %s\n", i, ja3ByHost_element->ip_string, info_of_element->ja3, print_cipher(info_of_element->unsafe_cipher) ); againstRepeat = 1; i++; } } if(num_ja3_server > 0) { HASH_ITER(hh, ja3ByHost_element->host_server_info_hasht, info_of_element, tmp2) { fprintf(out, "\t%-7d %-24s %-34s %s %s %s%s%s\n", i, ja3ByHost_element->ip_string, "", info_of_element->ja3, print_cipher(info_of_element->unsafe_cipher), ja3ByHost_element->dns_name[0] ? "[" : "", ja3ByHost_element->dns_name, ja3ByHost_element->dns_name[0] ? "]" : "" ); i++; } } } i = 1; fprintf(out, "\nIP/JA3 Distribution:\n"); fprintf(out, "%-15s %-39s %-26s\n", "", "JA3", "IP"); HASH_ITER(hh, hostByJA3C_ht, hostByJA3Element, tmp3) { againstRepeat = 0; HASH_ITER(hh, hostByJA3Element->ipToDNS_ht, innerHashEl, tmp4) { if(againstRepeat == 0) { fprintf(out, "\t%-7d JA3C %s", i, hostByJA3Element->ja3 ); fprintf(out, " %-15s %s\n", innerHashEl->ip_string, print_cipher(hostByJA3Element->unsafe_cipher) ); againstRepeat = 1; i++; } else { fprintf(out, "\t%45s", ""); fprintf(out, " %-15s %s\n", innerHashEl->ip_string, print_cipher(hostByJA3Element->unsafe_cipher) ); } } } HASH_ITER(hh, hostByJA3S_ht, hostByJA3Element, tmp3) { againstRepeat = 0; HASH_ITER(hh, hostByJA3Element->ipToDNS_ht, innerHashEl, tmp4) { if(againstRepeat == 0) { fprintf(out, "\t%-7d JA3S %s", i, hostByJA3Element->ja3 ); fprintf(out, " %-15s %-10s %s%s%s\n", innerHashEl->ip_string, print_cipher(hostByJA3Element->unsafe_cipher), innerHashEl->dns_name[0] ? "[" : "", innerHashEl->dns_name, innerHashEl->dns_name[0] ? "]" : "" ); againstRepeat = 1; i++; } else { fprintf(out, "\t%45s", ""); fprintf(out, " %-15s %-10s %s%s%s\n", innerHashEl->ip_string, print_cipher(hostByJA3Element->unsafe_cipher), innerHashEl->dns_name[0] ? "[" : "", innerHashEl->dns_name, innerHashEl->dns_name[0] ? "]" : "" ); } } } } fprintf(out, "\n\n"); //freeing the hash table HASH_ITER(hh, ja3ByHostsHashT, ja3ByHost_element, tmp) { HASH_ITER(hh, ja3ByHost_element->host_client_info_hasht, info_of_element, tmp2) { if(ja3ByHost_element->host_client_info_hasht) HASH_DEL(ja3ByHost_element->host_client_info_hasht, info_of_element); free(info_of_element); } HASH_ITER(hh, ja3ByHost_element->host_server_info_hasht, info_of_element, tmp2) { if(ja3ByHost_element->host_server_info_hasht) HASH_DEL(ja3ByHost_element->host_server_info_hasht, info_of_element); free(info_of_element); } HASH_DEL(ja3ByHostsHashT, ja3ByHost_element); free(ja3ByHost_element); } HASH_ITER(hh, hostByJA3C_ht, hostByJA3Element, tmp3) { HASH_ITER(hh, hostByJA3C_ht->ipToDNS_ht, innerHashEl, tmp4) { if(hostByJA3Element->ipToDNS_ht) HASH_DEL(hostByJA3Element->ipToDNS_ht, innerHashEl); free(innerHashEl); } HASH_DEL(hostByJA3C_ht, hostByJA3Element); free(hostByJA3Element); } hostByJA3Element = NULL; HASH_ITER(hh, hostByJA3S_ht, hostByJA3Element, tmp3) { HASH_ITER(hh, hostByJA3S_ht->ipToDNS_ht, innerHashEl, tmp4) { if(hostByJA3Element->ipToDNS_ht) HASH_DEL(hostByJA3Element->ipToDNS_ht, innerHashEl); free(innerHashEl); } HASH_DEL(hostByJA3S_ht, hostByJA3Element); free(hostByJA3Element); } } } /* Print all flows stats */ qsort(all_flows, num_flows, sizeof(struct flow_info), cmpFlows); if(verbose > 1) { for(i=0; i<num_flows; i++) printFlow(i+1, all_flows[i].flow, all_flows[i].thread_id); } for(thread_id = 0; thread_id < num_threads; thread_id++) { if(ndpi_thread_info[thread_id].workflow->stats.protocol_counter[0 /* 0 = Unknown */] > 0) { fprintf(out, "\n\nUndetected flows:%s\n", undetected_flows_deleted ? " (expired flows are not listed below)" : ""); break; } } num_flows = 0; for(thread_id = 0; thread_id < num_threads; thread_id++) { if(ndpi_thread_info[thread_id].workflow->stats.protocol_counter[0] > 0) { for(i=0; i<NUM_ROOTS; i++) ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], node_print_unknown_proto_walker, &thread_id); } } qsort(all_flows, num_flows, sizeof(struct flow_info), cmpFlows); for(i=0; i<num_flows; i++) printFlow(i+1, all_flows[i].flow, all_flows[i].thread_id); } else if(csv_fp != NULL) { int i; num_flows = 0; for(thread_id = 0; thread_id < num_threads; thread_id++) { for(i=0; i<NUM_ROOTS; i++) ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], node_print_known_proto_walker, &thread_id); } for(i=0; i<num_flows; i++) printFlow(i+1, all_flows[i].flow, all_flows[i].thread_id); } free(all_flows); } /* *********************************************** */ /** * @brief Print result */ static void printResults(u_int64_t processing_time_usec, u_int64_t setup_time_usec) { u_int32_t i; u_int64_t total_flow_bytes = 0; u_int32_t avg_pkt_size = 0; struct ndpi_stats cumulative_stats; int thread_id; char buf[32]; long long unsigned int breed_stats[NUM_BREEDS] = { 0 }; memset(&cumulative_stats, 0, sizeof(cumulative_stats)); for(thread_id = 0; thread_id < num_threads; thread_id++) { if((ndpi_thread_info[thread_id].workflow->stats.total_wire_bytes == 0) && (ndpi_thread_info[thread_id].workflow->stats.raw_packet_count == 0)) continue; for(i=0; i<NUM_ROOTS; i++) { ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], node_proto_guess_walker, &thread_id); if(verbose == 3) ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], port_stats_walker, &thread_id); } /* Stats aggregation */ cumulative_stats.guessed_flow_protocols += ndpi_thread_info[thread_id].workflow->stats.guessed_flow_protocols; cumulative_stats.raw_packet_count += ndpi_thread_info[thread_id].workflow->stats.raw_packet_count; cumulative_stats.ip_packet_count += ndpi_thread_info[thread_id].workflow->stats.ip_packet_count; cumulative_stats.total_wire_bytes += ndpi_thread_info[thread_id].workflow->stats.total_wire_bytes; cumulative_stats.total_ip_bytes += ndpi_thread_info[thread_id].workflow->stats.total_ip_bytes; cumulative_stats.total_discarded_bytes += ndpi_thread_info[thread_id].workflow->stats.total_discarded_bytes; for(i = 0; i < ndpi_get_num_supported_protocols(ndpi_thread_info[0].workflow->ndpi_struct); i++) { cumulative_stats.protocol_counter[i] += ndpi_thread_info[thread_id].workflow->stats.protocol_counter[i]; cumulative_stats.protocol_counter_bytes[i] += ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes[i]; cumulative_stats.protocol_flows[i] += ndpi_thread_info[thread_id].workflow->stats.protocol_flows[i]; } cumulative_stats.ndpi_flow_count += ndpi_thread_info[thread_id].workflow->stats.ndpi_flow_count; cumulative_stats.tcp_count += ndpi_thread_info[thread_id].workflow->stats.tcp_count; cumulative_stats.udp_count += ndpi_thread_info[thread_id].workflow->stats.udp_count; cumulative_stats.mpls_count += ndpi_thread_info[thread_id].workflow->stats.mpls_count; cumulative_stats.pppoe_count += ndpi_thread_info[thread_id].workflow->stats.pppoe_count; cumulative_stats.vlan_count += ndpi_thread_info[thread_id].workflow->stats.vlan_count; cumulative_stats.fragmented_count += ndpi_thread_info[thread_id].workflow->stats.fragmented_count; for(i = 0; i < sizeof(cumulative_stats.packet_len)/sizeof(cumulative_stats.packet_len[0]); i++) cumulative_stats.packet_len[i] += ndpi_thread_info[thread_id].workflow->stats.packet_len[i]; cumulative_stats.max_packet_len += ndpi_thread_info[thread_id].workflow->stats.max_packet_len; } if(cumulative_stats.total_wire_bytes == 0) goto free_stats; if(!quiet_mode) { printf("\nnDPI Memory statistics:\n"); printf("\tnDPI Memory (once): %-13s\n", formatBytes(ndpi_get_ndpi_detection_module_size(), buf, sizeof(buf))); printf("\tFlow Memory (per flow): %-13s\n", formatBytes(sizeof(struct ndpi_flow_struct), buf, sizeof(buf))); printf("\tActual Memory: %-13s\n", formatBytes(current_ndpi_memory, buf, sizeof(buf))); printf("\tPeak Memory: %-13s\n", formatBytes(max_ndpi_memory, buf, sizeof(buf))); printf("\tSetup Time: %lu msec\n", (unsigned long)(setup_time_usec/1000)); printf("\tPacket Processing Time: %lu msec\n", (unsigned long)(processing_time_usec/1000)); printf("\nTraffic statistics:\n"); printf("\tEthernet bytes: %-13llu (includes ethernet CRC/IFC/trailer)\n", (long long unsigned int)cumulative_stats.total_wire_bytes); printf("\tDiscarded bytes: %-13llu\n", (long long unsigned int)cumulative_stats.total_discarded_bytes); printf("\tIP packets: %-13llu of %llu packets total\n", (long long unsigned int)cumulative_stats.ip_packet_count, (long long unsigned int)cumulative_stats.raw_packet_count); /* In order to prevent Floating point exception in case of no traffic*/ if(cumulative_stats.total_ip_bytes && cumulative_stats.raw_packet_count) avg_pkt_size = (unsigned int)(cumulative_stats.total_ip_bytes/cumulative_stats.raw_packet_count); printf("\tIP bytes: %-13llu (avg pkt size %u bytes)\n", (long long unsigned int)cumulative_stats.total_ip_bytes,avg_pkt_size); printf("\tUnique flows: %-13u\n", cumulative_stats.ndpi_flow_count); printf("\tTCP Packets: %-13lu\n", (unsigned long)cumulative_stats.tcp_count); printf("\tUDP Packets: %-13lu\n", (unsigned long)cumulative_stats.udp_count); printf("\tVLAN Packets: %-13lu\n", (unsigned long)cumulative_stats.vlan_count); printf("\tMPLS Packets: %-13lu\n", (unsigned long)cumulative_stats.mpls_count); printf("\tPPPoE Packets: %-13lu\n", (unsigned long)cumulative_stats.pppoe_count); printf("\tFragmented Packets: %-13lu\n", (unsigned long)cumulative_stats.fragmented_count); printf("\tMax Packet size: %-13u\n", cumulative_stats.max_packet_len); printf("\tPacket Len < 64: %-13lu\n", (unsigned long)cumulative_stats.packet_len[0]); printf("\tPacket Len 64-128: %-13lu\n", (unsigned long)cumulative_stats.packet_len[1]); printf("\tPacket Len 128-256: %-13lu\n", (unsigned long)cumulative_stats.packet_len[2]); printf("\tPacket Len 256-1024: %-13lu\n", (unsigned long)cumulative_stats.packet_len[3]); printf("\tPacket Len 1024-1500: %-13lu\n", (unsigned long)cumulative_stats.packet_len[4]); printf("\tPacket Len > 1500: %-13lu\n", (unsigned long)cumulative_stats.packet_len[5]); if(processing_time_usec > 0) { char buf[32], buf1[32], when[64]; float t = (float)(cumulative_stats.ip_packet_count*1000000)/(float)processing_time_usec; float b = (float)(cumulative_stats.total_wire_bytes * 8 *1000000)/(float)processing_time_usec; float traffic_duration; struct tm result; if(live_capture) traffic_duration = processing_time_usec; else traffic_duration = (pcap_end.tv_sec*1000000 + pcap_end.tv_usec) - (pcap_start.tv_sec*1000000 + pcap_start.tv_usec); printf("\tnDPI throughput: %s pps / %s/sec\n", formatPackets(t, buf), formatTraffic(b, 1, buf1)); if(traffic_duration != 0) { t = (float)(cumulative_stats.ip_packet_count*1000000)/(float)traffic_duration; b = (float)(cumulative_stats.total_wire_bytes * 8 *1000000)/(float)traffic_duration; } else { t = 0; b = 0; } strftime(when, sizeof(when), "%d/%b/%Y %H:%M:%S", localtime_r(&pcap_start.tv_sec, &result)); printf("\tAnalysis begin: %s\n", when); strftime(when, sizeof(when), "%d/%b/%Y %H:%M:%S", localtime_r(&pcap_end.tv_sec, &result)); printf("\tAnalysis end: %s\n", when); printf("\tTraffic throughput: %s pps / %s/sec\n", formatPackets(t, buf), formatTraffic(b, 1, buf1)); printf("\tTraffic duration: %.3f sec\n", traffic_duration/1000000); } if(enable_protocol_guess) printf("\tGuessed flow protos: %-13u\n", cumulative_stats.guessed_flow_protocols); } if(!quiet_mode) printf("\n\nDetected protocols:\n"); for(i = 0; i <= ndpi_get_num_supported_protocols(ndpi_thread_info[0].workflow->ndpi_struct); i++) { ndpi_protocol_breed_t breed = ndpi_get_proto_breed(ndpi_thread_info[0].workflow->ndpi_struct, i); if(cumulative_stats.protocol_counter[i] > 0) { breed_stats[breed] += (long long unsigned int)cumulative_stats.protocol_counter_bytes[i]; if(results_file) fprintf(results_file, "%s\t%llu\t%llu\t%u\n", ndpi_get_proto_name(ndpi_thread_info[0].workflow->ndpi_struct, i), (long long unsigned int)cumulative_stats.protocol_counter[i], (long long unsigned int)cumulative_stats.protocol_counter_bytes[i], cumulative_stats.protocol_flows[i]); if((!quiet_mode)) { printf("\t%-20s packets: %-13llu bytes: %-13llu " "flows: %-13u\n", ndpi_get_proto_name(ndpi_thread_info[0].workflow->ndpi_struct, i), (long long unsigned int)cumulative_stats.protocol_counter[i], (long long unsigned int)cumulative_stats.protocol_counter_bytes[i], cumulative_stats.protocol_flows[i]); } total_flow_bytes += cumulative_stats.protocol_counter_bytes[i]; } } if((!quiet_mode)) { printf("\n\nProtocol statistics:\n"); for(i=0; i < NUM_BREEDS; i++) { if(breed_stats[i] > 0) { printf("\t%-20s %13llu bytes\n", ndpi_get_proto_breed_name(ndpi_thread_info[0].workflow->ndpi_struct, i), breed_stats[i]); } } } // printf("\n\nTotal Flow Traffic: %llu (diff: %llu)\n", total_flow_bytes, cumulative_stats.total_ip_bytes-total_flow_bytes); printFlowsStats(); if(verbose == 3) { HASH_SORT(srcStats, port_stats_sort); HASH_SORT(dstStats, port_stats_sort); printf("\n\nSource Ports Stats:\n"); printPortStats(srcStats); printf("\nDestination Ports Stats:\n"); printPortStats(dstStats); } free_stats: if(scannerHosts) { deleteScanners(scannerHosts); scannerHosts = NULL; } if(receivers) { deleteReceivers(receivers); receivers = NULL; } if(topReceivers) { deleteReceivers(topReceivers); topReceivers = NULL; } if(srcStats) { deletePortsStats(srcStats); srcStats = NULL; } if(dstStats) { deletePortsStats(dstStats); dstStats = NULL; } } /** * @brief Force a pcap_dispatch() or pcap_loop() call to return */ static void breakPcapLoop(u_int16_t thread_id) { #ifdef USE_DPDK dpdk_run_capture = 0; #else if(ndpi_thread_info[thread_id].workflow->pcap_handle != NULL) { pcap_breakloop(ndpi_thread_info[thread_id].workflow->pcap_handle); } #endif } /** * @brief Sigproc is executed for each packet in the pcap file */ void sigproc(int sig) { static int called = 0; int thread_id; if(called) return; else called = 1; shutdown_app = 1; for(thread_id=0; thread_id<num_threads; thread_id++) breakPcapLoop(thread_id); } /** * @brief Get the next pcap file from a passed playlist */ static int getNextPcapFileFromPlaylist(u_int16_t thread_id, char filename[], u_int32_t filename_len) { if(playlist_fp[thread_id] == NULL) { if((playlist_fp[thread_id] = fopen(_pcap_file[thread_id], "r")) == NULL) return -1; } next_line: if(fgets(filename, filename_len, playlist_fp[thread_id])) { int l = strlen(filename); if(filename[0] == '\0' || filename[0] == '#') goto next_line; if(filename[l-1] == '\n') filename[l-1] = '\0'; return 0; } else { fclose(playlist_fp[thread_id]); playlist_fp[thread_id] = NULL; return -1; } } /** * @brief Configure the pcap handle */ static void configurePcapHandle(pcap_t * pcap_handle) { if(bpfFilter != NULL) { struct bpf_program fcode; if(pcap_compile(pcap_handle, &fcode, bpfFilter, 1, 0xFFFFFF00) < 0) { printf("pcap_compile error: '%s'\n", pcap_geterr(pcap_handle)); } else { if(pcap_setfilter(pcap_handle, &fcode) < 0) { printf("pcap_setfilter error: '%s'\n", pcap_geterr(pcap_handle)); } else printf("Successfully set BPF filter to '%s'\n", bpfFilter); } } } /** * @brief Open a pcap file or a specified device - Always returns a valid pcap_t */ static pcap_t * openPcapFileOrDevice(u_int16_t thread_id, const u_char * pcap_file) { u_int snaplen = 1536; int promisc = 1; char pcap_error_buffer[PCAP_ERRBUF_SIZE]; pcap_t * pcap_handle = NULL; /* trying to open a live interface */ #ifdef USE_DPDK struct rte_mempool *mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS, MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); if(mbuf_pool == NULL) rte_exit(EXIT_FAILURE, "Cannot create mbuf pool: are hugepages ok?\n"); if(dpdk_port_init(dpdk_port_id, mbuf_pool) != 0) rte_exit(EXIT_FAILURE, "DPDK: Cannot init port %u: please see README.dpdk\n", dpdk_port_id); #else /* Trying to open the interface */ if((pcap_handle = pcap_open_live((char*)pcap_file, snaplen, promisc, 500, pcap_error_buffer)) == NULL) { capture_for = capture_until = 0; live_capture = 0; num_threads = 1; /* Open pcap files in single threads mode */ /* Trying to open a pcap file */ if((pcap_handle = pcap_open_offline((char*)pcap_file, pcap_error_buffer)) == NULL) { char filename[256] = { 0 }; if(strstr((char*)pcap_file, (char*)".pcap")) printf("ERROR: could not open pcap file %s: %s\n", pcap_file, pcap_error_buffer); /* Trying to open as a playlist as last attempt */ else if((getNextPcapFileFromPlaylist(thread_id, filename, sizeof(filename)) != 0) || ((pcap_handle = pcap_open_offline(filename, pcap_error_buffer)) == NULL)) { /* This probably was a bad interface name, printing a generic error */ printf("ERROR: could not open %s: %s\n", filename, pcap_error_buffer); exit(-1); } else { if((!quiet_mode)) printf("Reading packets from playlist %s...\n", pcap_file); } } else { if((!quiet_mode)) printf("Reading packets from pcap file %s...\n", pcap_file); } } else { live_capture = 1; if((!quiet_mode)) { #ifdef USE_DPDK printf("Capturing from DPDK (port 0)...\n"); #else printf("Capturing live traffic from device %s...\n", pcap_file); #endif } } configurePcapHandle(pcap_handle); #endif /* !DPDK */ if(capture_for > 0) { if((!quiet_mode)) printf("Capturing traffic up to %u seconds\n", (unsigned int)capture_for); #ifndef WIN32 alarm(capture_for); signal(SIGALRM, sigproc); #endif } return pcap_handle; } /** * @brief Check pcap packet */ static void ndpi_process_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) { struct ndpi_proto p; u_int16_t thread_id = *((u_int16_t*)args); /* allocate an exact size buffer to check overflows */ uint8_t *packet_checked = malloc(header->caplen); memcpy(packet_checked, packet, header->caplen); p = ndpi_workflow_process_packet(ndpi_thread_info[thread_id].workflow, header, packet_checked); if(!pcap_start.tv_sec) pcap_start.tv_sec = header->ts.tv_sec, pcap_start.tv_usec = header->ts.tv_usec; pcap_end.tv_sec = header->ts.tv_sec, pcap_end.tv_usec = header->ts.tv_usec; /* Idle flows cleanup */ if(live_capture) { if(ndpi_thread_info[thread_id].last_idle_scan_time + IDLE_SCAN_PERIOD < ndpi_thread_info[thread_id].workflow->last_time) { /* scan for idle flows */ ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[ndpi_thread_info[thread_id].idle_scan_idx], node_idle_scan_walker, &thread_id); /* remove idle flows (unfortunately we cannot do this inline) */ while(ndpi_thread_info[thread_id].num_idle_flows > 0) { /* search and delete the idle flow from the "ndpi_flow_root" (see struct reader thread) - here flows are the node of a b-tree */ ndpi_tdelete(ndpi_thread_info[thread_id].idle_flows[--ndpi_thread_info[thread_id].num_idle_flows], &ndpi_thread_info[thread_id].workflow->ndpi_flows_root[ndpi_thread_info[thread_id].idle_scan_idx], ndpi_workflow_node_cmp); /* free the memory associated to idle flow in "idle_flows" - (see struct reader thread)*/ ndpi_free_flow_info_half(ndpi_thread_info[thread_id].idle_flows[ndpi_thread_info[thread_id].num_idle_flows]); ndpi_free(ndpi_thread_info[thread_id].idle_flows[ndpi_thread_info[thread_id].num_idle_flows]); } if(++ndpi_thread_info[thread_id].idle_scan_idx == ndpi_thread_info[thread_id].workflow->prefs.num_roots) ndpi_thread_info[thread_id].idle_scan_idx = 0; ndpi_thread_info[thread_id].last_idle_scan_time = ndpi_thread_info[thread_id].workflow->last_time; } } #ifdef DEBUG_TRACE if(trace) fprintf(trace, "Found %u bytes packet %u.%u\n", header->caplen, p.app_protocol, p.master_protocol); #endif if(extcap_dumper && ((extcap_packet_filter == (u_int16_t)-1) || (p.app_protocol == extcap_packet_filter) || (p.master_protocol == extcap_packet_filter) ) ) { struct pcap_pkthdr h; uint32_t *crc, delta = sizeof(struct ndpi_packet_trailer) + 4 /* ethernet trailer */; struct ndpi_packet_trailer *trailer; memcpy(&h, header, sizeof(h)); if(h.caplen > (sizeof(extcap_buf)-sizeof(struct ndpi_packet_trailer) - 4)) { printf("INTERNAL ERROR: caplen=%u\n", h.caplen); h.caplen = sizeof(extcap_buf)-sizeof(struct ndpi_packet_trailer) - 4; } trailer = (struct ndpi_packet_trailer*)&extcap_buf[h.caplen]; memcpy(extcap_buf, packet, h.caplen); memset(trailer, 0, sizeof(struct ndpi_packet_trailer)); trailer->magic = htonl(0x19680924); trailer->master_protocol = htons(p.master_protocol), trailer->app_protocol = htons(p.app_protocol); ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct, p, trailer->name, sizeof(trailer->name)); crc = (uint32_t*)&extcap_buf[h.caplen+sizeof(struct ndpi_packet_trailer)]; *crc = ethernet_crc32((const void*)extcap_buf, h.caplen+sizeof(struct ndpi_packet_trailer)); h.caplen += delta, h.len += delta; #ifdef DEBUG_TRACE if(trace) fprintf(trace, "Dumping %u bytes packet\n", h.caplen); #endif pcap_dump((u_char*)extcap_dumper, &h, (const u_char *)extcap_buf); pcap_dump_flush(extcap_dumper); } /* check for buffer changes */ if(memcmp(packet, packet_checked, header->caplen) != 0) printf("INTERNAL ERROR: ingress packet was modified by nDPI: this should not happen [thread_id=%u, packetId=%lu, caplen=%u]\n", thread_id, (unsigned long)ndpi_thread_info[thread_id].workflow->stats.raw_packet_count, header->caplen); if((pcap_end.tv_sec-pcap_start.tv_sec) > pcap_analysis_duration) { int i; u_int64_t processing_time_usec, setup_time_usec; gettimeofday(&end, NULL); processing_time_usec = end.tv_sec*1000000 + end.tv_usec - (begin.tv_sec*1000000 + begin.tv_usec); setup_time_usec = begin.tv_sec*1000000 + begin.tv_usec - (startup_time.tv_sec*1000000 + startup_time.tv_usec); printResults(processing_time_usec, setup_time_usec); for(i=0; i<ndpi_thread_info[thread_id].workflow->prefs.num_roots; i++) { ndpi_tdestroy(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], ndpi_flow_info_freer); ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i] = NULL; memset(&ndpi_thread_info[thread_id].workflow->stats, 0, sizeof(struct ndpi_stats)); } if(!quiet_mode) printf("\n-------------------------------------------\n\n"); memcpy(&begin, &end, sizeof(begin)); memcpy(&pcap_start, &pcap_end, sizeof(pcap_start)); } /* Leave the free as last statement to avoid crashes when ndpi_detection_giveup() is called above by printResults() */ free(packet_checked); } /** * @brief Call pcap_loop() to process packets from a live capture or savefile */ static void runPcapLoop(u_int16_t thread_id) { if((!shutdown_app) && (ndpi_thread_info[thread_id].workflow->pcap_handle != NULL)) if(pcap_loop(ndpi_thread_info[thread_id].workflow->pcap_handle, -1, &ndpi_process_packet, (u_char*)&thread_id) < 0) printf("Error while reading pcap file: '%s'\n", pcap_geterr(ndpi_thread_info[thread_id].workflow->pcap_handle)); } /** * @brief Process a running thread */ void * processing_thread(void *_thread_id) { long thread_id = (long) _thread_id; char pcap_error_buffer[PCAP_ERRBUF_SIZE]; #if defined(linux) && defined(HAVE_PTHREAD_SETAFFINITY_NP) if(core_affinity[thread_id] >= 0) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core_affinity[thread_id], &cpuset); if(pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0) fprintf(stderr, "Error while binding thread %ld to core %d\n", thread_id, core_affinity[thread_id]); else { if((!quiet_mode)) printf("Running thread %ld on core %d...\n", thread_id, core_affinity[thread_id]); } } else #endif if((!quiet_mode)) printf("Running thread %ld...\n", thread_id); #ifdef USE_DPDK while(dpdk_run_capture) { struct rte_mbuf *bufs[BURST_SIZE]; u_int16_t num = rte_eth_rx_burst(dpdk_port_id, 0, bufs, BURST_SIZE); u_int i; if(num == 0) { usleep(1); continue; } for(i = 0; i < PREFETCH_OFFSET && i < num; i++) rte_prefetch0(rte_pktmbuf_mtod(bufs[i], void *)); for(i = 0; i < num; i++) { char *data = rte_pktmbuf_mtod(bufs[i], char *); int len = rte_pktmbuf_pkt_len(bufs[i]); struct pcap_pkthdr h; h.len = h.caplen = len; gettimeofday(&h.ts, NULL); ndpi_process_packet((u_char*)&thread_id, &h, (const u_char *)data); rte_pktmbuf_free(bufs[i]); } } #else pcap_loop: runPcapLoop(thread_id); if(playlist_fp[thread_id] != NULL) { /* playlist: read next file */ char filename[256]; if(getNextPcapFileFromPlaylist(thread_id, filename, sizeof(filename)) == 0 && (ndpi_thread_info[thread_id].workflow->pcap_handle = pcap_open_offline(filename, pcap_error_buffer)) != NULL) { configurePcapHandle(ndpi_thread_info[thread_id].workflow->pcap_handle); goto pcap_loop; } } #endif return NULL; } /** * @brief Begin, process, end detection process */ void test_lib() { u_int64_t processing_time_usec, setup_time_usec; long thread_id; #ifdef DEBUG_TRACE if(trace) fprintf(trace, "Num threads: %d\n", num_threads); #endif for(thread_id = 0; thread_id < num_threads; thread_id++) { pcap_t *cap; #ifdef DEBUG_TRACE if(trace) fprintf(trace, "Opening %s\n", (const u_char*)_pcap_file[thread_id]); #endif cap = openPcapFileOrDevice(thread_id, (const u_char*)_pcap_file[thread_id]); setupDetection(thread_id, cap); } gettimeofday(&begin, NULL); int status; void * thd_res; /* Running processing threads */ for(thread_id = 0; thread_id < num_threads; thread_id++) { status = pthread_create(&ndpi_thread_info[thread_id].pthread, NULL, processing_thread, (void *) thread_id); /* check pthreade_create return value */ if(status != 0) { fprintf(stderr, "error on create %ld thread\n", thread_id); exit(-1); } } /* Waiting for completion */ for(thread_id = 0; thread_id < num_threads; thread_id++) { status = pthread_join(ndpi_thread_info[thread_id].pthread, &thd_res); /* check pthreade_join return value */ if(status != 0) { fprintf(stderr, "error on join %ld thread\n", thread_id); exit(-1); } if(thd_res != NULL) { fprintf(stderr, "error on returned value of %ld joined thread\n", thread_id); exit(-1); } } gettimeofday(&end, NULL); processing_time_usec = end.tv_sec*1000000 + end.tv_usec - (begin.tv_sec*1000000 + begin.tv_usec); setup_time_usec = begin.tv_sec*1000000 + begin.tv_usec - (startup_time.tv_sec*1000000 + startup_time.tv_usec); /* Printing cumulative results */ printResults(processing_time_usec, setup_time_usec); for(thread_id = 0; thread_id < num_threads; thread_id++) { if(ndpi_thread_info[thread_id].workflow->pcap_handle != NULL) pcap_close(ndpi_thread_info[thread_id].workflow->pcap_handle); terminateDetection(thread_id); } } /* *********************************************** */ static void bitmapUnitTest() { u_int32_t val, i, j; for(i=0; i<32; i++) { NDPI_ZERO_BIT(val); NDPI_SET_BIT(val, i); assert(NDPI_ISSET_BIT(val, i)); for(j=0; j<32; j++) { if(j != i) { assert(!NDPI_ISSET_BIT(val, j)); } } } } /* *********************************************** */ void automataUnitTest() { void *automa = ndpi_init_automa(); assert(automa); assert(ndpi_add_string_to_automa(automa, "hello") == 0); assert(ndpi_add_string_to_automa(automa, "world") == 0); ndpi_finalize_automa(automa); assert(ndpi_match_string(automa, "This is the wonderful world of nDPI") == 1); ndpi_free_automa(automa); } /* *********************************************** */ void serializerUnitTest() { ndpi_serializer serializer, deserializer; int i; u_int8_t trace = 0; assert(ndpi_init_serializer(&serializer, ndpi_serialization_format_tlv) != -1); for(i=0; i<16; i++) { char kbuf[32], vbuf[32]; assert(ndpi_serialize_uint32_uint32(&serializer, i, i*i) != -1); snprintf(kbuf, sizeof(kbuf), "Hello %d", i); snprintf(vbuf, sizeof(vbuf), "World %d", i); assert(ndpi_serialize_uint32_string(&serializer, i, "Hello") != -1); assert(ndpi_serialize_string_string(&serializer, kbuf, vbuf) != -1); assert(ndpi_serialize_string_uint32(&serializer, kbuf, i*i) != -1); assert(ndpi_serialize_string_float(&serializer, kbuf, (float)(i*i), "%f") != -1); } if(trace) printf("Serialization size: %u\n", ndpi_serializer_get_buffer_len(&serializer)); assert(ndpi_init_deserializer(&deserializer, &serializer) != -1); while(1) { ndpi_serialization_type kt, et; et = ndpi_deserialize_get_item_type(&deserializer, &kt); if(et == ndpi_serialization_unknown) break; else { u_int32_t k32, v32; ndpi_string ks, vs; float vf; switch(kt) { case ndpi_serialization_uint32: ndpi_deserialize_key_uint32(&deserializer, &k32); if(trace) printf("%u=", k32); break; case ndpi_serialization_string: ndpi_deserialize_key_string(&deserializer, &ks); if (trace) { u_int8_t bkp = ks.str[ks.str_len]; ks.str[ks.str_len] = '\0'; printf("%s=", ks.str); ks.str[ks.str_len] = bkp; } break; default: printf("Unsupported TLV key type %u\n", kt); return; } switch(et) { case ndpi_serialization_uint32: assert(ndpi_deserialize_value_uint32(&deserializer, &v32) != -1); if(trace) printf("%u\n", v32); break; case ndpi_serialization_string: assert(ndpi_deserialize_value_string(&deserializer, &vs) != -1); if(trace) { u_int8_t bkp = vs.str[vs.str_len]; vs.str[vs.str_len] = '\0'; printf("%s\n", vs.str); vs.str[vs.str_len] = bkp; } break; case ndpi_serialization_float: assert(ndpi_deserialize_value_float(&deserializer, &vf) != -1); if(trace) printf("%f\n", vf); break; default: if (trace) printf("\n"); printf("serializerUnitTest: unsupported type %u detected!\n", et); return; break; } } ndpi_deserialize_next(&deserializer); } ndpi_term_serializer(&serializer); } /* *********************************************** */ // #define RUN_DATA_ANALYSIS_THEN_QUIT 1 void analyzeUnitTest() { struct ndpi_analyze_struct *s = ndpi_alloc_data_analysis(32); u_int32_t i; for(i=0; i<256; i++) { ndpi_data_add_value(s, rand()*i); // ndpi_data_add_value(s, i+1); } // ndpi_data_print_window_values(s); #ifdef RUN_DATA_ANALYSIS_THEN_QUIT printf("Average: [all: %f][window: %f]\n", ndpi_data_average(s), ndpi_data_window_average(s)); printf("Entropy: %f\n", ndpi_data_entropy(s)); printf("Min/Max: %u/%u\n", ndpi_data_min(s), ndpi_data_max(s)); #endif ndpi_free_data_analysis(s); #ifdef RUN_DATA_ANALYSIS_THEN_QUIT exit(0); #endif } /* *********************************************** */ /** * @brief Initialize port array */ void bpf_filter_port_array_init(int array[], int size) { int i; for(i=0; i<size; i++) array[i] = INIT_VAL; } /* *********************************************** */ /** * @brief Initialize host array */ void bpf_filter_host_array_init(const char *array[48], int size) { int i; for(i=0; i<size; i++) array[i] = NULL; } /* *********************************************** */ /** * @brief Add host to host filter array */ void bpf_filter_host_array_add(const char *filter_array[48], int size, const char *host) { int i; int r; for(i=0; i<size; i++) { if((filter_array[i] != NULL) && (r = strcmp(filter_array[i], host)) == 0) return; if(filter_array[i] == NULL) { filter_array[i] = host; return; } } fprintf(stderr,"bpf_filter_host_array_add: max array size is reached!\n"); exit(-1); } /* *********************************************** */ /** * @brief Add port to port filter array */ void bpf_filter_port_array_add(int filter_array[], int size, int port) { int i; for(i=0; i<size; i++) { if(filter_array[i] == port) return; if(filter_array[i] == INIT_VAL) { filter_array[i] = port; return; } } fprintf(stderr,"bpf_filter_port_array_add: max array size is reached!\n"); exit(-1); } /* *********************************************** */ /** @brief MAIN FUNCTION **/ #ifdef APP_HAS_OWN_MAIN int orginal_main(int argc, char **argv) { #else int main(int argc, char **argv) { #endif int i; if(ndpi_get_api_version() != NDPI_API_VERSION) { printf("nDPI Library version mismatch: please make sure this code and the nDPI library are in sync\n"); return(-1); } /* Internal checks */ bitmapUnitTest(); automataUnitTest(); serializerUnitTest(); analyzeUnitTest(); ndpi_self_check_host_match(); gettimeofday(&startup_time, NULL); ndpi_info_mod = ndpi_init_detection_module(ndpi_no_prefs); if(ndpi_info_mod == NULL) return -1; memset(ndpi_thread_info, 0, sizeof(ndpi_thread_info)); parseOptions(argc, argv); if(!quiet_mode) { printf("\n-----------------------------------------------------------\n" "* NOTE: This is demo app to show *some* nDPI features.\n" "* In this demo we have implemented only some basic features\n" "* just to show you what you can do with the library. Feel \n" "* free to extend it and send us the patches for inclusion\n" "------------------------------------------------------------\n\n"); printf("Using nDPI (%s) [%d thread(s)]\n", ndpi_revision(), num_threads); } signal(SIGINT, sigproc); for(i=0; i<num_loops; i++) test_lib(); if(results_path) free(results_path); if(results_file) fclose(results_file); if(extcap_dumper) pcap_dump_close(extcap_dumper); if(ndpi_info_mod) ndpi_exit_detection_module(ndpi_info_mod); if(csv_fp) fclose(csv_fp); return 0; } #ifdef WIN32 #ifndef __GNUC__ #define EPOCHFILETIME (116444736000000000i64) #else #define EPOCHFILETIME (116444736000000000LL) #endif /** @brief Timezone **/ struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; /** @brief Set time **/ int gettimeofday(struct timeval *tv, struct timezone *tz) { FILETIME ft; LARGE_INTEGER li; __int64 t; static int tzflag; if(tv) { GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; t = li.QuadPart; /* In 100-nanosecond intervals */ t -= EPOCHFILETIME; /* Offset to the Epoch time */ t /= 10; /* In microseconds */ tv->tv_sec = (long)(t / 1000000); tv->tv_usec = (long)(t % 1000000); } if(tz) { if(!tzflag) { _tzset(); tzflag++; } tz->tz_minuteswest = _timezone / 60; tz->tz_dsttime = _daylight; } return 0; } #endif /* WIN32 */
./CrossVul/dataset_final_sorted/CWE-125/c/good_4215_0
crossvul-cpp_data_good_926_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % 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/property.h" #include "magick/blob.h" #include "magick/cache-view.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/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const 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); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if ((width == 0) || (height == 0)) return(threshold_image); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically performs image thresholding % dependent on which method you specify. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const Image *image,const double *histogram) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p++; } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(image,histogram); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property); return(BilevelImage(image,QuantumRange*threshold/100.0)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; 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); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); 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); if ((channel & SyncChannels) != 0) { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 : QuantumRange); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? 0 : QuantumRange); else SetPixelAlpha(q,(MagickRealType) GetPixelAlpha(q) <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold ? 0 : QuantumRange); q++; } 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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* Black threshold image. */ 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) && ((MagickRealType) GetPixelRed(q) < threshold.red)) SetPixelRed(q,0); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) < threshold.green)) SetPixelGreen(q,0); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) < threshold.blue)) SetPixelBlue(q,0); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) < threshold.opacity)) SetPixelOpacity(q,0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x) < threshold.index)) SetPixelIndex(indexes+x,0); q++; } 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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; 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); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); 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,ClampPixel((MagickRealType) GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampPixel((MagickRealType) GetPixelIndex( indexes+x))); q++; } 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,ClampImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attribute, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *) NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(map); for (threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { attribute=GetXMLTreeAttribute(threshold, "map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold, "alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } /* The map has been found -- allocate a Threshold Map to return */ map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap)); if (map == (ThresholdMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; /* Assign basic attributeibutes. */ attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels, "divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array. */ content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { char *p; register ssize_t i; /* Parse levels into integer array. */ for (i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; 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 (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); 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 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++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1)); l = t/d; t = t-l*d; SetPixelRed(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red))); } if (levels.green) { t = (ssize_t) (QuantumScale*GetPixelGreen(q)* (levels.green*d+1)); l = t/d; t = t-l*d; SetPixelGreen(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green))); } if (levels.blue) { t = (ssize_t) (QuantumScale*GetPixelBlue(q)* (levels.blue*d+1)); l = t/d; t = t-l*d; SetPixelBlue(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue))); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))* (levels.opacity*d+1)); l = t/d; t = t-l*d; SetPixelOpacity(q,ClampToQuantum((MagickRealType) ((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/ levels.opacity))); } if (levels.index) { t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)* (levels.index*d+1)); l = t/d; t = t-l*d; SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index))); } q++; } 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,DitherImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImageChannel method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon) % MagickBooleanType PerceptibleImageChannel(Image *image, % const ChannelType channel,const double epsilon) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon) { MagickBooleanType status; status=PerceptibleImageChannel(image,DefaultChannels,epsilon); return(status); } MagickExport MagickBooleanType PerceptibleImageChannel(Image *image, const ChannelType channel,const double epsilon) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; ExceptionInfo *exception; 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); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); q++; } return(SyncImage(image)); } /* Perceptible image. */ status=MagickTrue; progress=0; exception=(&image->exception); 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,PerceptibleThreshold(GetPixelRed(q),epsilon)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x), epsilon)); q++; } 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,PerceptibleImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; 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 (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == CompositeChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); 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(); MagickBooleanType sync; 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++) { IndexPacket index; MagickRealType intensity; intensity=GetPixelIntensity(image,q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } 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++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) GetPixelRed(q) < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) GetPixelRed(q) > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) GetPixelGreen(q) < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) GetPixelGreen(q) > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) GetPixelBlue(q) < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) GetPixelBlue(q) > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) GetPixelOpacity(q) < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) GetPixelOpacity(q) > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold.index ? 0 : QuantumRange); q++; } 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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* White threshold image. */ 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) && ((MagickRealType) GetPixelRed(q) > threshold.red)) SetPixelRed(q,QuantumRange); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) > threshold.green)) SetPixelGreen(q,QuantumRange); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) > threshold.blue)) SetPixelBlue(q,QuantumRange); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) > threshold.opacity)) SetPixelOpacity(q,QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index) SetPixelIndex(indexes+x,QuantumRange); q++; } 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,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_926_0